How to redirect to https using .htaccess

How to redirect to https using .htaccess

If you’re looking for a quick and simple method to redirect your plain HTTP site visitors to the SSL edition without fancy server-side configuration (or asking your host for help), this can be easily done through the ubiquitous .htaccess file present and supported on most Apache-powered hosting services – nginx supports htaccess as well, but its configuration directives use a different structure.

Create the .htaccess file in the root of your website folder (most often public_html/) if you don’t have one and add the following content at its beginning (try not to overlap different configuration blocks used as lines are processed sequentially):

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

If the %{HTTPS} environment variable is not available on your system, you can also use the (less fancy) method of checking the port:

RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HTTP_HOST} www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ https://www.domain.tld/$1 [L,R=301]

The downside of this latter method is that it requires adapting/updating the domain name in the rules (and only works if there is no custom port configuration used).

Leave a Reply