首页 文章

使用代理传递的nginx和尾部斜杠

提问于
浏览
11

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

我想要做的是当用户访问 http://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 时,我得到了正确的结果(来自apache的404) . 当我访问 http://correct.name.gr:8000/test/asd 时,我得到了正确的结果(来自nginx的404) . 当我访问 http://correct.name.gr:8000/test/register123 时,我得到了正确的结果(来自apache的404) .

The problem is when I visit http://correct.name.gr:8000/test/register. I get a 301 response and I am redirected to http://localhost/test/register/ (notice the trailing slash and of course the 'localhost')!!!

我没有对nginx做任何其他配置来放置斜杠或类似的东西 . 你知道这是什么问题吗?我希望 http://correct.name.gr:8000/test/register 通过代理到apache来正常工作(或者如果不可能,至少发出404错误而不是重定向到用户的localhost) .

Update 1 :我试过了 http://correct.name.gr:8000/test/register 来自一台不同于昨天坏行为的计算机..好吧,它起作用了:我刚收到301响应,指出我正确的 http://correct.name.gr:8000/test/register/ !如何使用一台计算机而不是另一台计算机(我在两台计算机上使用相同的浏览器 - Chrome)?明天我会再试一次从第三个测试来看看这个行为 .

谢谢 !

2 回答

  • 1

    你有没有试过玩server_name_in_redirect

    但是,我发现你通过谷歌提问,因为我使用尾部斜杠运行相同的问题 . Nginx使用尾部斜杠强制301到同一个URL .

  • 3

    我的猜测是您的上游服务器(apache或您的脚本)触发了重定向到 absolute url http://localhost/test/register/ . 因为在 proxy_pass 指令中使用了 http://127.0.0.1 ,所以nginx找不到域名的匹配项并返回 Location 标头 .

    我认为正确的解决方案是,如果重定向是内部网址,则不使用绝对重定向 . 这总是一个很好的做法 .

    但是,如果不更改上游服务器,则有两种快速解决方案 .

    您可以使用

    proxy_pass http://localhost;
    

    这将告诉nginx上游的域名是 localhost . 然后当nginx从上游找到 Location 标头中的那个部分时,它将知道将 http://localhost 替换为 http://correct.name.gr:8000 .

    另一个是添加一个 proxy_redirect 行来强制nginx用 http://localhost/ 重写任何位置 Headers .

    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

相关问题