Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Redirect HTTP to HTTPS in Nginx

Get an SSL certificate and add a permanent redirect so visitors always use HTTPS.

SSL and Security2 min read7 screenshots

What you need

  • Nginx on Ubuntu or another Linux system.
  • A valid SSL certificate (Let's Encrypt is free).
  • SSH or terminal access with sudo.
  • A domain that points to your server.

Step 1: Install Nginx

sudo apt install nginx
Installing Nginx

Step 2: Get an SSL certificate

Install Certbot with the Nginx plugin:

sudo apt install certbot python3-certbot-nginx
Installing Certbot

Request the certificate:

sudo certbot --nginx
Getting the SSL certificate

Certbot asks if you want to redirect HTTP to HTTPS. If you choose yes, it adds the redirect for you. The steps below show how to do it by hand, or how to check it.

Step 3: Set up the redirect

Open your site config, for example /etc/nginx/sites-available/example.com (or /etc/nginx/conf.d/example.com.conf):

sudo nano /etc/nginx/sites-available/example.com

Add a server block for port 80 that sends everything to HTTPS:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}
The Nginx redirect configuration
  • listen 80 catches the plain HTTP requests.
  • return 301 sends a permanent redirect, which search engines understand.
  • $request_uri keeps the path and query string.

The HTTPS server block (port 443 with your certificate) must also exist and use server_name example.com www.example.com. Also redirect https://www.example.com to your main domain if you want one address.

Step 4: Check Nginx

sudo systemctl status nginx
Checking the Nginx status

Test the configuration:

sudo nginx -t
Testing the Nginx configuration

Step 5: Restart Nginx

sudo systemctl restart nginx
Restarting Nginx

Test it

curl -I http://example.com

The answer should show 301 Moved Permanently and a Location: https://example.com/ header.

Quick recap

  • Get a certificate, add a port 80 server block with return 301, and reload Nginx.