In this article, we will see how to configure Nginx to redirect a non-www URL to the www address, and vice-versa.

Go to the configuration file for your virtual host, which is normally found at /etc/nginx/sites-available.

To redirect non-www to www

server {
    if ($host = example.app) {
        return 301 https://www.$host$request_uri;
    } # managed by Certbot


    listen 80 ;
    listen [::]:80 ;
    server_name example.app;
    return 404; # managed by Certbot

}

To redirect www to non-www

server {
    if ($host = www.example.app) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 ;
    listen [::]:80 ;
    server_name example.app;
    return 404; # managed by Certbot

}

Once all changes are done, make sure to check the syntax using the command:

nginx -t

Then reload your Nginx

sudo systemctl reload nginx
OR
sudo systemctl restart nginx