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

Found this article helpful?

TutsCoder tutorials are free and ad-light — supported by readers like you. Buy me a coffee (or two ☕☕) as a token of appreciation and help keep Angular & Node.js content coming!

One-time. No subscription. 100% optional. 🙏 Every coffee counts!

Leave a Comment

Your email will not be published. Spam-free zone. ✌️

Available for Projects

Need Help With Your
Angular or Node.js Project?

7+ years of MEAN Stack experience. I build scalable Angular 21 apps, Node.js APIs, and SaaS products — delivered on time, every time.

7+ Years MEAN Stack Angular 21 + Nx Expert 20+ Projects Delivered Remote / Freelance