If you have a secure certificate (SSL) on your website, you can automatically redirect visitors to the secured (HTTPS) version of your website.

For Apache

Using the following code in your .htaccess file or site conf file to automatically redirect visitors to the HTTPS version of your site:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,QSA,R=permanent]

If you have an existing .htaccess file:

  • Do not duplicate the RewriteEngine On line.
  • Make sure the lines starting with RewriteCond and RewriteRule immediately follow the pre-existing RewriteEngine On.

For Nginx

Find the server block in your site configuration and comment out the following lines:

  • listen 80 default_server;
  • listen [::]:80 default_server ipv6only=on;

We are going to configure the server block to listen on port 443 with SSL enabled instead of the default 80.

Within the server block, add the following (changing example.com to use your domain, as well as changing the location of your SSL certificate if your setup differs from Let's Encrypt).

listen 443 ssl;

server_name example.com www.example.com;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

Outside the previous server block, create a new server block with the following to enable the redirect:

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}