Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I've got two options (return and rewrite) for redirection and I'm not sure which one is recommenced (performance, SEO etc.):

## Redirect from non-www to www
server {
        server_name example.com;
        # Option 1
        return 301 $scheme://$host$request_uri;

        # Option 2
        rewrite ^ http://$host$request_uri? permanent;

## Default server config

server {
        listen default_server;
        root        /www;
        server_name www.example.com;

with option 2 I've noted that it seems to work with curl but it's not redirecting when called by a browser and the return code is that of a temporary redirect despite the rewrite directive being set to permanent:

 curl -I example.com
 HTTP/1.1 302 Moved Temporarily
 Server: nginx
 Location: http://www.example.com/
share|improve this question

1 Answer 1

up vote 9 down vote accepted

Your option 1:

return 301 $scheme://$host$request_uri;

Is exactly what you want.

Not sure why the rewrite ^ http://$host$request_uri? permanent; line would result in a 302 instead of 301. That's the proper syntax to force it to return a 301.

share|improve this answer
I had to add "listen" directive to the first server block. It works fine however when I try to access the admin backend (Wordpress - wp-admin) there is some kind of loop and I can't get into the login page. Any ideas? –  HTF Jul 12 '12 at 11:06
That would probably be better dealt with in a separate question. Sounds like both your software (wordpress) and nginx are doing some redirecting, resulting in a loop. –  Gnarfoz Jul 12 '12 at 15:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.