Redirect HTTP to HTTPS in Nginx

Before we redirect all http to https in Nginx, we should have installed an SSL certificate successfully.

server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}

This listens on port 80. It’s also the port 80 default server. It’s assumed that it’s the only server block listening on port 80.

The server_name is _, which matches any hostname used.

Finally, we return a 301 redirect to the https version of whatever URI was requested. We know all requests reaching this server block is http, because it only listens for port 80 requests.

We can redirect only specific sites also. This is better if you have multiple apps/sites and not all of them should be forced to use SSL certificates.

server {
    listen 80 default_server;

    server_name _;

    return 301 https://www.cheapglasses123.com$request_uri;
}

Here we listen on port 80 for http requests, but we don’t make it the default server. Instead, it is only listening for requests made to the hostname www.cheapglasses123.com  (where the Host HTTP header is set to foo.com).

It returns a 301 redirect to the https version of the URI given, but hard-codes the hostname (www.cheapglasses123.com).

Just modify cheapglasses123.com.conf, save, and restart Nginx.