On Apache and LiteSpeed web servers (see web server software), a small text file called .htaccess lets you change server behaviour without access to the main configuration. It is powerful – and unforgiving. Keep examples simple and test after every change.
301 redirects
# Single pages
Redirect 301 /old-page.html https://www.example.com/new-page
Redirect 301 /blog/old-post/ https://www.example.com/new-postUse one-to-one redirects when you move content. See moving a website without losing rankings.
Force HTTPS and choose www or not
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]Some hosts already handle this in the control panel – check before adding rules, to avoid redirect loops.
Custom error pages
ErrorDocument 404 /404.htmlBrowser caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>The IfModule wrapper prevents errors if the module is not available.
Security headers
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>Safety rules
- Download a copy of the current file before every change.
- Change one thing at a time and test the site immediately.
- Avoid complex rewrite rules you do not understand – ask an AI to explain them line by line first.
Frequently asked questions
Where is my .htaccess file?
In the root folder of your website, often public_html. It starts with a dot, so it may be hidden in file managers – enable “show hidden files”.
My site shows a 500 error after editing .htaccess. What now?
Restore the previous version of the file immediately. A 500 error usually means a syntax error or a directive your host does not allow.