Allan & Steve are the chubby founders of LessEverything. This is their blog, hear them rant, praise, give advice and talk about Just Stuff, Less Accounting, Lovd by Less, More Honey, Events, Less Memories, Code, Business, Design, Marketing

Redirect from www to non-www using Nginx

written by Steven Bristol on April 9th, 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;
 }

11 Responses to “Redirect from www to non-www using Nginx”

  1. She-ra April 9th, 2008

    Nice post and it’s worth noting that those redirects should always be 301s unless you know what you’re getting into.

  2. Steven Bristol April 9th, 2008

    @she-ra

    Good point. Actually, the word “permanent” in the config snippet tells Nginx to do a 301, not a 302.

    steve

  3. Brennan April 9th, 2008

    I just stick it in its own server block..

    server { listen 80; server_name www.oftengloomy.com; rewrite ^/(.*) http://oftengloomy.com permanent; }

  4. Steven Bristol April 10th, 2008

    @Brennan,

    That’s a good idea.

  5. ashchan April 11th, 2008

    I prefer Brennan’s way, and used it on several sites.

  6. Steven Bristol April 11th, 2008

    @ashchan,

    Thanks for your comment. :)

    steve

  7. Ronnie April 24th, 2008

    Thanks for the post. Igor Sysoev states here that the $1 can be replaced by $uri so that the rewrite could be written as “rewrite ^ http://your_domain.com/$uri permanent;”.

  8. Steven Bristol April 24th, 2008

    @Ronnie,

    Thanks for the tip! :)

  9. Ronnie April 24th, 2008

    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.

  10. Hendry Lee September 28th, 2008

    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?

  11. Steven Bristol September 28th, 2008

    @Hendry,

    It does support regex. I’m not sure I understand your second question, but you may have multiple if/redirect statements.

    steve

Sorry, comments are closed for this article.