nginx redirect to www.domain

Solution 1:

You're doing it the hard way. Here's the easy way.

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

server {
    listen 80;
    server_name  www.example.com;
    #The rest of your configuration goes here#
}

Solution 2:

It's better to use return instead of rewrite, because it's faster.

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

server {
    listen 80;
    server_name     www.example.com;
    [...]
}

This way, we also send the client a proper status code, so that he asks the right domain in the next request.