Nginx Library

A repository of Nginx-related articles

Www/no-www rewrite rules

There are many ways to rewrite www urls to their non-www versions in nginx. Here one that’s Igor-approved and works well on my setup :

WWW to Non-WWW:

#301 redirect www to non-www
server {
    listen   [::]:80;
    server_name  www.domain.com;
    rewrite ^    http://domain.com$request_uri? permanent;
}

server {
    listen   [::]:80;
    server_name  domain.com;
    .........................................
    .........................................
}

Non-WWW to WWW:

#301 redirect non-www to www
server {
    listen   [::]:80;
    server_name  domain.com;
    rewrite ^    http://www.domain.com$request_uri? permanent;
}

server {
    listen   [::]:80;
    server_name  www.domain.com;
    .........................................
    .........................................
}
If you find this article helpful, please consider making a donation.

Comments