http - nginx 和带有代理传递的尾部斜线

标签 http nginx reverse-proxy

我正在为 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)。

问题出在我访问 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 或您的脚本)触发了重定向到绝对 url http://localhost/test/register/ .因为你用 http://127.0.0.1在你的proxy_pass指令,nginx 找不到匹配的域名并返回 Location header 原样。

我认为正确的解决方案是在重定向到内部 URL 时不使用绝对重定向。这始终是一个好习惯。

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

你可以使用

proxy_pass http://localhost;

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

另外一个是加一个proxy_redirect强制 nginx 使用 http://localhost/ 重写任何位置 header 的行

 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

关于http - nginx 和带有代理传递的尾部斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422558/

相关文章:

Nginx:重写不适用于图像的规则

cloud - 在 Varnish 反向代理中使用具有多个 IP 的域名

nginx - 反向代理背后的Keycloak

linux - Nginx Proxy_Pass 到 CDN 与直接访问 CDN。优点,缺点,速度是否较慢或对服务器有负面影响?

web-services - Nginx SSL 直通不适用于 REST Web 服务

http - 使用 Varnish 缓存并改变自定义设置的 HTTP header

html - 使用 $routeProvider 是否节省网络带宽?

javascript - Node js 错误 : Protocol "https:" not supported. 预期为 "http:"

HTTP 413 请求实体太大

node.js - 从 nginx proxy_pass 中删除路径的开头