How to redirect HTTP to HTTPS on Nginx

Endrit Qerreti

Endrit Qerreti

In this tutorial, you will learn how to redirect http to https on Nginx.

If you have a site and you want to redirect all your visitors that are using http protocol, to a safer protocol in this case https, then you can easily do so by following this tutorial.

Redirect HTTP to HTTPS on Nginx

Redirecting your visitors from http to https version of your site is easy, and it can be done by setting up the redirection rule on your nginx configuration file.

Step 1 - Open Nginx configuration file

First you need to choose where you want to add the redirect function.

If you are going to redirect all your sites on your server, then you need to add the return function on your nginx configuration file.

sudo nano /etc/nginx/nginx.conf

In case you want to redirect only a single site on your server, then you can easily do so by editing your site's configuration file.

sudo nano /etc/nginx/sites-enabled/mysite.conf

Step 2 - Redirect HTTP to HTTPS

Redirect any requests made to port 80 on your server.

If you want to redirect all sites on your server, then you need to setup the redirection on your server block.

For example, the server block should look like this.

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

Redirect only a single site.

If you want to setup the redirect only for a single site, then you need to add the return function on your site's configuration file.

Your site's nginx configuration file is located in sites-enabled directory. To redirect http to https only for one site, then add return function on.

/etc/nginx/sites-enabled/mysite.conf

Server block for your site should look like this.

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

replace owlhowto.com with your domain name.

Save changes by pressing CTRL + X , and then confirm with Y, finally press enter.

Step 3 - Restart Nginx

Next, proceed to check for syntax errors on your configuration files, before restarting nginx.

sudo nginx -t

Restart nginx if syntax is correct and no errors encountered.

sudo systemctl restart nginx

Conclusion

In this tutorial, you learned how to redirect http to https on Nginx. We showed how to redirect all requests made on your server, and how to redirect requests made to a single site only.