How to redirect non-www to www and vice versa on Nginx

How to redirect non-www to www and vice versa on Nginx

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

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment