Www/no-www rewrite rules for nginx


nginx logoThere 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:

[code]#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;
…………………………………..
…………………………………..
}[/code]

Non-WWW to WWW:

[code]#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;
…………………………………..
…………………………………..
}[/code]