Apache htaccess: Force Domain HTTPS/SSL protocol

In order to redirect all users from the unsecure HTTP to the secure HTTPS connection, you need to edit your .htaccess file. Usually, it is located in the root of your project (e.g., httpdocs folder).

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

First of all, you need to check whether or not the apache rewrite module (mod_rewrite) is enabled. Of course, you can skip the check, but it is strongly recommended that you’d rather not (I would say it goes against best practices). Some day you might want to move your blog/website/etc. to another hosting. So what may happen then, is that the new hosting would not support this module or you might need to enable it by yourself.

Secondly, whenever the rewrite engine itself is turned off, it will be switched on by the “RewriteEngine On” command in the listing above. The next line “RewriteCond %{HTTPS} !=on” will ensure that the user protocol is checked, as to whether it a HTTPS one or not. If the user types in the address starting with HTTP, the “RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]” will be applied. The latter says that the document you are looking for is Moved Permanently (protocol status code 301) to the same address, but with the HTTPS protocol instead.

Similarly, to the code provided above, you are able to redirect your subdomain from HTTP to secure HTTPS protocol. All you need to do is to change carefully “blog.wlsc.de” for your subdomain.

RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^blog\.wlsc\.de$ [NC]
RewriteRule ^ https://blog.wlsc.de%{REQUEST_URI} [R=301,L]

Voila! Your redirect from the unsecure HTTP protocol to the secure HTTPS is ready!!

Now you walk on the safe side! Take care.

Contents