Redirect from www to non-www using Nginx
written by Steven on April 09, 2008
Let's say you want to redirect users from the www sub-domain of your website to direct access via the non-sub-domain url. Nginx makes it really easy to do.
Just add this to your server{} block:
if ($host != 'your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
This actually will redirect any sub-domain to the non-sub-domain url. But what if, like Less Accounting, your site has user accounts for sub-domains or you have other valid sub-domains, but you still want to get users away from www?
Just add this to your server{} block:
if ($host = 'www.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
Learn how LessEverything built their consultancy to over $1,000,000 annual revenue at LessMoney Conference, June 7th in Tampa Florida. Each attendee will get early access to our upcoming ebook as well.
Leave a Comment
About Steven
Popular Articles
Subscribe

Steven Bristol has written code for the past 20 years. He like green vegetables and kittens, oh and butterflies too. He loves to throw ninja stars at his enemies.

13 Comments
Nice post and it’s worth noting that those redirects should always be 301s unless you know what you’re getting into.
@she-ra
Good point. Actually, the word “permanent” in the config snippet tells Nginx to do a 301, not a 302.
steve
I just stick it in its own server block..
server {
listen 80;
server_name www.oftengloomy.com;
rewrite ^/(.*) http://oftengloomy.com permanent;
}
@Brennan,
That’s a good idea.
I prefer Brennan’s way, and used it on several sites.
@ashchan,
Thanks for your comment. :)
steve
Thanks for the post. Igor Sysoev states [here](http://www.ruby-forum.com/topic/145480#644118) that the $1 can be replaced by $uri so that the rewrite could be written as “rewrite ^ http://your_domain.com/$uri permanent;”.
@Ronnie,
Thanks for the tip! :)
A small correction to my previous comment:
There should be no slash before $uri. The rewrite line should be “rewrite ^ http://your_domain.com$uri permanent;”. The previous line works, but it will produce a double slash because $uri contains a leading slash.
Does nginx support regex on this statement? What if I have a few vhosts and want to redirect it just once, instead of multiple times? Is it possible?
@Hendry,
It does support regex. I’m not sure I understand your second question, but you may have multiple if/redirect statements.
steve
@Hendry
You can use regex like
if ($host ~ ^www) {
rewrite (.*) http://example.com$1 permanent;
}
This has changed since version 0.9.1, see:
http://nginx.org/en/docs/http/converting_rewrite_rules.html