Redirect www to non www domain in Nginx Ubuntu

To redirect users from the “www” to the “non-www” version of a domain, create a new server block in the Nginx configuration file. For example, if you want your site to redirect from www.yourdomain.com to yourdomain.com for both HTTP and HTTPS schemes then you need to follow the below-mentioned steps:

Open the config file of your site (/etc/nginx/sites-available/yourdomain.com):

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

Add the following section at the last of the config file:

server {
    server_name www.yourdomain.com;
    return 301 $https://yourdomain.com$request_uri;
}

server {
    server_name www.yourdomain.com;
    listen [::]:443 ssl http2;
    listen 443 ssl http2;
    return 301 https://yourdomain.com$request_uri;
}

Above, we have added a new server block for the www version of the yourdomain.

Save the configuration file, and then test it for errors. You can use the sudo nginx -t command to test the syntax errors:

sudo nginx -t

Restart Nginx, if the test is successful, you can use the sudo systemctl restart nginx command to restart it.:

sudo systemctl restart nginx

This configuration will redirect all requests from www.yourdomain.com to yourdomain.com. The return 301 statement tells the browser to update its cached URL with the new one so that any future requests for the old URL will automatically go to the new one i.e your site will now make a 301 redirect now from the www domain to non-www domain for both HTTP and HTTPS schemes.

After making changes, make sure to test them to ensure they’re functioning properly.