如何在NGINX中重定向URL [英] How to redirect a url in NGINX

查看:170
本文介绍了如何在NGINX中重定向URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将每个 http://test.com 请求重定向到

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;

但在浏览器中显示

  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.

我的服务器块看起来像

 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;
            }
    }

推荐答案

执行所需操作的最佳方法是添加另一个服务器块:

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;
}

并按如下所示编辑主服务器块server_name变量:

And edit your main server block server_name variable as following:

server_name  www.test.com;

重要:新的server块是执行此操作的正确方法,邪恶,因此将其替换为return.

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.

这篇关于如何在NGINX中重定向URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆