Rewrite HTTP to HTTPS using .htaccess

If your website is hosted using Apache and mod_rewrite is enabled for you to use, this is how you can use an .htaccess file to redirect any http visits to your site to the https version of the same URL.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</IfModule>

Analysis

Here’s a breakdown of what this all means:

<IfModule mod_rewrite.c>

<IfModule …> prevents Apache parsing configuration for mod_rewrite if it isn’t enabled for us to use in .htaccess. You’ll get an HTTP 500 error if Apache encounters configuration it doesn’t understand.

RewriteEngine On

RewriteEngine tells Apache to activate the Rewrite module for the directory our .htaccess is in.

RewriteCond %{HTTPS} off

RewriteCond is a conditional that must evaluate to true or our subsequent RewriteRule will not execute. It evaluates to true if the value of the %{HTTPS} variable contains the string off. The %{HTTPS} variable (documented under RewriteCond) contains the text on if the connection is using SSL/TLS or off if it isn’t.

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

Finally, the RewriteRule is the instruction that rewrites the incoming URL and sends an HTTP redirect back to the client. It breaks down as follows: