带有代理传球的nginx和尾随斜杠 [英] nginx and trailing slash with proxy pass

查看:21
本文介绍了带有代理传球的nginx和尾随斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的nginx 1.4.1配置如下:

server {
    listen       8000;
    server_name  correct.name.gr;

    location /test/register {
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://127.0.0.1;
    }
}

我想要做的是,当用户visthttp://correct.name.gr:8000/test/register/时,他们应该被代理到运行在端口80上的Apache.

当我访问http://correct.name.gr:8000/test/register/时,我得到正确的结果(index.php)。 当我访问http://correct.name.gr:8000/test/register/asd时,我得到了正确的结果(来自阿帕奇的404)。 当我访问http://correct.name.gr:8000/test/asd时,我得到了正确的结果(来自nginx的404)。 当我访问http://correct.name.gr:8000/test/register123时,我得到了正确的结果(404来自阿帕奇)。

问题是当我访问http://correct.name.gr:8000/test/register时。我收到了301响应,我被重定向到http://localhost/test/register/(注意尾部的斜杠,当然还有‘localhost’)!

我没有对nginx进行任何其他配置,以放置尾部斜杠或类似的东西。你知道问题出在哪里吗?我希望http://correct.name.gr:8000/test/register通过代理到Apache来正常工作(如果不可能,至少发出404错误,而不是重定向到用户的本地主机)。

更新1:我从另一台计算机尝试http://correct.name.gr:8000/test/register,而不是昨天发生不良行为的那台计算机。好的,它起作用了:我刚刚收到了一个301响应,它将我指向正确的http://correct.name.gr:8000/test/register/!怎么可能在一台电脑上工作,而不是在另一台电脑上工作(我在两台电脑上使用相同的浏览器-Chrome)?我明天将再次尝试从第三个测试,以查看行为。

谢谢!

apache

我的猜测是您的上游服务器(推荐答案或您的脚本)触发了到绝对URLhttp://localhost/test/register/的重定向。因为您在proxy_pass指令中使用http://127.0.0.1,所以nginx找不到与域名匹配的项,并按原样返回Location头。

我认为正确的解决方案是,如果重定向指向内部URL,则不要使用绝对重定向。这始终是一种良好的做法。

但是,在不更改上游服务器的情况下,有两种快速解决方案。

您可以使用

proxy_pass http://localhost;

这会告诉nginx上游的域名是localhost。然后,当nginx在来自上游的Location头中找到该部分时,它将知道将http://localhost替换为http://correct.name.gr:8000

另一个方法是添加一个proxy_redirect行,强制nginx重写任何包含http://localhost/的Location头部。

 proxy_pass http://127.0.0.1;
 proxy_redirect http://localhost/ /;

我更喜欢第一个解决方案,因为它更简单。使用proxy_pass http://localhost;不会产生DNS查找开销,因为nginx在启动Web服务器时会提前进行查找。

引用:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect

这篇关于带有代理传球的nginx和尾随斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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