【问题标题】:Nginx redirect to an external URLNginx 重定向到外部 URL
【发布时间】:2012-08-02 14:34:02
【问题描述】:

我要做的是将所有请求路由到/rdr/extern_url,以通过我的网络服务器重定向到extern_url,而不是通过PHP。

location /rdr {
    rewrite ^/rdr/(.*)$ $1 permanent;
}

如果我访问 http://localhost/rdr/http://google.com 我的浏览器告诉我,这里出了什么问题:

Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.

如何正确重定向?

【问题讨论】:

    标签: redirect nginx rewrite


    【解决方案1】:

    简单检查:

    $ curl -si 'http://localhost/rdr/http://www.google.com' | head -8
    HTTP/1.1 301 Moved Permanently
    Server: nginx/1.2.0
    Date: Sun, 05 Aug 2012 09:33:14 GMT
    Content-Type: text/html
    Content-Length: 184
    Connection: keep-alive
    Location: http:/www.google.com
    

    如您所见,Location 的方案后只有一个斜杠。

    将以下指令添加到server后:

    merge_slashes off;
    

    我们会得到正确的答复:

    $ curl -si 'http://localhost/rdr/http://www.google.com' | head -8
    HTTP/1.1 301 Moved Permanently
    Server: nginx/1.2.0
    Date: Sun, 05 Aug 2012 09:36:56 GMT
    Content-Type: text/html
    Content-Length: 184
    Connection: keep-alive
    Location: http://www.google.com
    

    从 cmets 中可以清楚地看出,您可能希望将没有架构的主机名传递给重定向服务。要解决这个问题,您需要定义两个位置来分别处理这两种情况:

    server {
      listen 80;
      server_name localhost;
      merge_slashes off;
    
      location /rdr {
        location /rdr/http:// {
          rewrite ^/rdr/(.*)$ $1 permanent;
        }
        rewrite ^/rdr/(.*)$ http://$1 permanent;
      }
    }
    

    在这里,我将/rdr/http:// 定义为/rdr 的子位置,只是为了将重定向器服务保持在一个块中——在server 级别创建两个位置是完全有效的。

    【讨论】:

    • 我尝试在服务器上下文中添加merge_slashes off,但我仍然得到一个斜杠(重新启动 nginx 后)。顺便说一句,使用 curl 的好主意,我只在我的浏览器上测试它们。
    • 如您所见,它在我的设置中无缝运行。我建议您将问题本地化。使用唯一的server 对同一 Nginx 版本进行全新设置,看看会发生什么。检查“错误”日志,打开调试日志。
    • 如果开头没有http://怎么办? http://localhost/rdr/google.com
    • 如果开头没有http://,那么会是301Location: www.google.com,也就是说,你的浏览器会请求http://localhost/www.google.com(请不要删除你的cmets : 让读者很难掌握讨论的流程)
    • 你知道如何解决这个问题吗?
    猜你喜欢
    • 2013-11-23
    • 2017-12-11
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2019-10-23
    • 2015-02-14
    相关资源
    最近更新 更多