Redirect HTTP to HTTPS automatically

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 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;


ssl_certificate /etc/letsencrypt/live/;
ssl_certificate_key /etc/letsencrypt/live/;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

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

server {
    listen 80;
    return 301 https://$host$request_uri;
Enjoying this content? Subscribe for more
Subscribe now

Subscribe to be notified of new content and support Pinky promise that I won't sell your email.