How to redirect a url in NGINX

Amal Kumar S picture Amal Kumar S · Apr 24, 2012 · Viewed 279.9k times · Source

I need to redirect every http://test.com request to http://www.test.com. How can this be done.

In the server block I tried adding

 rewrite ^/(.*) http://www.test.com/$1 permanent;

but in browser it says

  The page isn't redirecting properly

  Firefox has detected that the server is redirecting the request for 
  this address in a way that will never complete.

my server block looks like

 server {
            listen       80;
            server_name  test.com;
            client_max_body_size   10M;
            client_body_buffer_size   128k;

            root       /home/test/test/public;
            passenger_enabled on;
            rails_env production;

            #rewrite ^/(.*) http://www.test.com/$1 permanent;
            #rewrite ^(.*)$ $scheme://www.test.com$1;

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                    root   html;
            }
    }

Answer

Dmitry Verhoturov picture Dmitry Verhoturov · Apr 24, 2012

Best way to do what you want is to add another server block:

server {
        #implemented by default, change if you need different ip or port
        #listen *:80 | *:8000;
        server_name test.com;
        return 301 $scheme://www.test.com$request_uri;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

Important: New server block is the right way to do this, if is evil. You must use locations and servers instead of if if it's possible. Rewrite is sometimes evil too, so replaced it with return.