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 2

  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

Post a Comment

Your email is never published nor shared. Required fields are marked *