Several methods exist to redirect traffic from HTTP to HTTPS automaticaly.

Apache

From virtual host

The definition fo the redirection is simple, we must specify that all connection on standard port must be rewrite to HTTPS protocol.

<VirtualHost *:80>
   ...
   ServerName subdomain.domain.tld
   ...
   RedirectMatch permanent ^/(.*)$ https://subdomain.domain.tld/$1
</VirtualHost>

All HTTP traffic is now redirected to HTTPS.

From .htaccess

The apache module mod_rewrite must be activated to use redirection.

Url Rewriting

The following command can check/activate it :

sudo a2enmod rewrite

If this module was not activated, you must restart Apache server :

sudo service apache2 restart

.htaccess

The following rules must be added in your .htaccess to activate a complete redirection :

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

Attention: If you have multiple domains, all traffic will be redirect in HTTPS. You will have an error if you don't have valid certificate !

To prevent this problem, you can specify the domain concerned by the traffic redirection :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain.domain.tld [NC]
RewriteCond %{HTTPS} off
RewriteCond (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

NGinx

It is very simple to force the redirection with NGinx. After you have add your site configuration to accept HTTPS traffic, you redirect all HTTP traffic with this in nginx config :

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}

Attention: If you have multiple domains, all traffic will be redirect in HTTPS. You will have an error if you don't have valid certificate !

To prevent this, you can specify the domains concerned :

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name subdomain.domain.tld
    return 301 https://$server_name$request_uri;
}

Next Post Previous Post