How to Redirect 'http' to 'https' in NGINX ?

Here we will learn how to redirect all http request to https in nginx server. Assuming you have successfully installed ssl and can access https manually.

a blue street sign sitting next to a brick wall
Photo by Stefan Heinemann on Unsplash

First Method:

This is the easiest one ! 🙂

Find below codes in your websites vhost.

server {
    listen  *:80;
server_name domain.tld www.domain.tld;
#
#
#
#
#
#}

Now make sure that code looks like below :

server {
    listen  *:80;
server_name domain.tld www.domain.tld;
#
#
rewrite        ^ https://$server_name$request_uri? permanent;
#
#
}

Second Method:

Find below codes in your websites vhost.

server {
    listen  *:80;
server_name domain.tld www.domain.tld;
#
#
#
#
#
#}

Now make sure that code looks like below :

server {
    listen  *:80;
server_name domain.tld www.domain.tld;
#
#
    if ( $scheme = "http" ) {
    rewrite  ^/(.*)$  https://$host/$1 permanent;
    }
#
#
}

Thank You.