How to redirect a URL in Nginx

I need to redirect every request to How can this be done.

In the server block I tried adding

rewrite ^/(.*)$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;
            client_max_body_size   10M;
            client_body_buffer_size   128k;

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

            #rewrite ^/(.*)$1 permanent;
            #rewrite ^(.*)$ $scheme://$1;

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


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;
        return 301 $scheme://$request_uri;

And edit your main server block server_name variable as following:


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.

Source : Link , Question Author : Amal Kumar S , Answer Author : coffeemakr

Leave a Comment