Free, independent guides since 2010

Code

.htaccess basics: redirects, HTTPS and caching on Apache

What the .htaccess file does on Apache and LiteSpeed servers, with safe examples for 301 redirects, forcing HTTPS, removing www, custom error pages, caching and security headers.

<guide section="Code" type="guide" read="1 min"/>

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

Plain text
# Single pages
Redirect 301 /old-page.html https://www.example.com/new-page
Redirect 301 /blog/old-post/ https://www.example.com/new-post

Use one-to-one redirects when you move content. See moving a website without losing rankings.

Force HTTPS and choose www or not

Plain text
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

Plain text
ErrorDocument 404 /404.html

Browser caching

Plain text
<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

Plain text
<IfModule mod_headers.c>
  Header set X-Content-Type-Options "nosniff"
  Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

Safety rules

  1. Download a copy of the current file before every change.
  2. Change one thing at a time and test the site immediately.
  3. 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.