How to force HTTPS traffic using htaccess

The htaccess rule below shows how to force all traffic to go over HTTPS, rather than HTTP.

This assumes you have correctly setup a certificate and traffic can be served over HTTPS. That is, loads the website correctly.

It also assumes your website is being run using apache, which uses a special file called ‘.htaccess’ for configuration.

To use, simply copy into the .htaccess file at the root (top level) of your website.


<IfModule mod_rewrite.c>
RewriteEngine On
# force https
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

If you also want to force the use of www. (recommended) simply change to.

RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]