How To Redirect HTTP to HTTPS in NGINX

Sometimes you may need to redirect HTTP to HTTPs or enforce HTTPS on your website. In this article, we will look at how to redirect HTTP to HTTPS in NGINX.


How To Redirect HTTP to HTTPS in NGINX

Here are the steps to redirect HTTP to HTTPS in NGINX.


1. Open NGINX configuration file

Open terminal and run the following command to open NGINX server configuration file.

$ sudo vi /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/sites-enabled/website.conf then open its configuration with the following command

$ sudo vi /etc/nginx/sites-enabled/website.conf

Alternatively, you can also open the default virtual host configuration file.

$ sudo vi /etc/nginx/sites-enabled/default

Also read : How to Configure Basic Authentication in NGINX


2. Redirect HTTP to HTTPS

There are multiple ways to redirect HTTP to HTTPS.

Here is the server configuration if you want to redirect all URL to HTTPS.

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

In the above code, we specify the following

  • Listen 80: Listen to all HTTP traffic on Port 80
  • Server_name _;: Match any hostname
  • Return 301: Indicates that this is a permanent redirect
  • https://$host$request_uri: Redirect to the HTTPS version of requested URL

If you want to redirect a specific website or domain, modify server name directive as shown below. Replace example.com with your domain name.

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

If you want to redirect only a specific URL (e.g. index.html), add a rewrite statement in its location block, as shown below. Replace example.com with your domain name.

Location /index.html {
       rewrite ^/index.html$ https://example.com/index.html redirect;
}

Also read : How to Install Let’s Encrypt in NGINX


3. Restart NGINX Server

Run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

Hopefully, this article will help you redirect HTTP to HTTPS in NGINX. Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free.

mm

About Ubiq

Ubiq is a powerful dashboard & reporting platform for small & medium businesses. Build dashboards, charts & reports for your business in minutes. Get insights from data quickly. Try it for free today!