28 August 2018

Force SSL encryption for both domain and subdomains

Server configuration

There are more ways to redirect domain from HTTP to secure HTTPS protocol to force SSL encryption. One and most likely the best, also recommended by the Apache Documentation, is to write the redirect down to main server configuration file.

<VirtualHost *:80>
    ServerName domain.tld
    ServerAlias www.domain.tld
    Redirect / https://domain.tld/
</VirtualHost>

<VirtualHost *:443>
    ServerName domain.tld
    #SSL
</VirtualHost>

Replace domain.tld with your domain name and #SSL with your actual SSL configuration.


PHP redirect

Another way is to put the redirect inside the PHP code.

if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
    $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirect);
    exit();
}

Apache module

If none of the previous solutions worked for you, there is still the mod_rewrite Apache module. You can use it by creating a .htaccess file in your domain's or subdomain's root directory, but in this example I am using RewriteEngine to redirect both domain and all subdomains from http://www.domain.tld to https://domain.tld.

DirectoryIndex index.php
AddDefaultCharset UTF-8
Options +FollowSymlinks -MultiViews

RewriteEngine On
RewriteCond %{SERVER_PORT} =80
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Note that the first three lines are not necessary.