How to force Nginx to redirect site name without-www to ‘www’

If you have a domain, ‘example.com’ and you want it to be available both when a user enters, ‘http://example.com’ and ‘http://www.example.com’, and you are running Nginx on your server, you can do so by updating the Nginx conf file for that Site. This file can usually be found in /etc/nginx/sites-available/ folder.
Open the file and add a new ‘Server’ Block on the top.

To redirect, site name with www to without www :

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

Replace the www.example.com above with your domain name (with ‘www’ ofcourse )

To redirect site name, without-www to www :

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

Similarly, replace ‘example.com’ with the domain name (without www)

Save the file and test the nginx configuration, before restarting Nginx and applying the new configuration :

nginx -t

If this shows no errors, then restart Nginx to apply the settings :

service nginx restart