nGinx non-www to www redirect

Nitin Srivastava asked:

I have been working with apache for years and now wanted to move to nGinx keeping in view the performance everyone on internet seems to be talking about. But I its very frustrating for me for not being able to rewrite a non-www url to www i.e. example.com to www.example.com

I have referred to all the posts on StackOverflow and have tried their configurations. Somehow the system does not seem to work. I have wasted more than 2 hours in this and need help from you. My nGinx version is 1.2.1. This was 15sec work in Apache. I have somehow started missing apache.

My answer:


Taken from my site www.yes-www.org:

server {
    listen [::]:80;
    server_name example.com;
    return 301 http://www.example.com$request_uri;
}

Your other server block should not respond to example.com, but only www.example.com.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.