An .htaccess file is a configuration file that the Apache web server reads in each folder of your site. Without touching the server's global configuration, it lets you control how your website responds: redirect old URLs to new ones with 301 redirects, force HTTPS, unify the domain to www or non-www, enable gzip compression and browser cache so pages load faster, add security headers, and block access to private files such as .env or .git. It is one of the most powerful tools on shared hosting. One key detail: .htaccess is exclusive to Apache. If your server runs Nginx, this file is ignored entirely and you have to write the rules in nginx.conf instead. Before using it, confirm with your host that you are on Apache.
What an .htaccess is for
- 301 redirects: move a page without losing your Google ranking.
- Forced HTTPS: nobody enters over insecure http://.
- www or non-www: stop Google from seeing two versions of the same site.
- Speed: gzip shrinks files and cache avoids repeat downloads.
- Security: block sensitive files and add headers that stop common attacks.
- Custom errors: show your own 404 page instead of Apache's ugly default.
How redirects work
For simple path-to-path redirects the Redirect 301 /old /new directive is enough; it comes from the mod_alias module and needs no regular expressions. When the logic is more complex (force HTTPS, add or remove www, redirect by pattern) mod_rewrite steps in with RewriteCond and RewriteRule. That is where you use regex, and the most typical mistake is forgetting to escape the dot: in a regular expression a bare dot means "any character", so to represent a real dot you must write it as \\. with a backslash.
Reference: most-used .htaccess directives
| Directive | What it does | Example |
|---|---|---|
RewriteEngine | Turns the URL rewriting engine on or off. Goes before any RewriteRule. | RewriteEngine On |
RewriteCond | Adds a condition that is evaluated before applying the RewriteRule that follows. | RewriteCond %{HTTP_HOST} ^www\\.domain\\.com$ [NC] |
RewriteRule | Defines a pattern and where to rewrite or redirect when it matches. | RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] |
Redirect 301 | Simple permanent redirect from one path to another (mod_alias, no regex). | Redirect 301 /old /new |
ErrorDocument | Defines a custom page for an HTTP error code. | ErrorDocument 404 /404.html |
Header set | Adds or replaces an HTTP header on the response (mod_headers). | Header set X-Frame-Options "SAMEORIGIN" |
ExpiresByType | Sets how long the browser caches a given file type (mod_expires). | ExpiresByType image/png "access plus 1 year" |
Before you upload it
Always back up the .htaccess you already had: if the new one has a syntax error, Apache returns a 500 error across the whole site, not on a single page. With the backup you restore and recover instantly. Upload it via FTP or from your hosting file manager to the site root, and test an old URL to confirm it redirects correctly.