Nginx redirect www.example.com requests to example.com or vice versa

Add following configuration directive if you want to redirect www.example.com to example.com

server {
    server_name  www.example.com;
    rewrite ^(.*) http://example.com$1 permanent;
}

server {
    server_name  example.com;
    Put here your domain hosting configuration.
}

Add following configuration directive if you want to redirect example.com to www.example.com

server {
    server_name  example.com;
    rewrite ^(.*) http://www.example.com$1 permanent;
}

server {
    server_name  www.example.com;
    Put here your domain hosting configuration.
}

Comments 7

  1. Justin wrote:

    This is was I was looking for, thanks for posting. I wrote about it and included this url in my post as a reference.

    Posted 01 Mar 2008 at 5:22 pm
  2. vanderkerkoff wrote:

    How do you achieve what I believe is called ‘masking’ using this technique?

    When the user enters example.com into the address bar they go to http://www.example.com but example.com stays in the address bar?

    Anyone got any ideas?

    Posted 25 Jun 2008 at 2:39 pm
  3. Colin wrote:

    Yer the bomb! this totally fixed my current conundrum… thanks again!

    Posted 27 Jul 2008 at 9:17 am
  4. Yann wrote:

    I am grateful. This was a no pain solution to my problem.

    Posted 13 Aug 2008 at 2:16 pm
  5. Travis Reeder wrote:

    Exactly what I needed. Thanks!

    Posted 02 Oct 2008 at 2:03 am
  6. Christopher Fritz wrote:

    Nice. This is exactly what I needed. Thanks for providing this information for others! Perhaps because of my set up, I had to include the “listen” line, so my redirect looks like (using a fake IP address in this example):

    server {
    listen 120.120.120.120:80;
    server_name http://www.example.com;
    rewrite ^(.*) http://www.example.com$1 permanent;
    }

    server {
    listen 120.120.120.120:80;
    server_name example.com;
    …etc…
    }

    In other words, if the main server {} area has the “listen”, be sure to add it to the server {} area with the redirect. (It really does make sense, but it can be easy to miss!)

    Posted 03 Oct 2008 at 4:49 am
  7. indiehead wrote:

    you are a genius!

    thanks for this, really needed it,

    John.

    Posted 15 Oct 2008 at 12:40 pm