2013-07-02 59 views
10

我使用下面的配置nginx的1.4.1:nginx的与代理斜线传球

 
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/它们应该被代理到它运行的Apache我想要做的就是端口80.

当我访问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从不同的计算机比昨天我有不良行为的一个..那么,它的工作:我刚刚说向我指出了正确的http://correct.name.gr:8000/test/register/ 301响应!如何从一台计算机上工作而不是从另一台计算机上工作(我在两台计算机上使用相同的浏览器 - Chrome)?我明天再试一次,从第三个测试中看到行为。

谢谢!

回答

3

我的猜测是你的上游服务器(apache或你的脚本)触发了重定向到绝对 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/

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

1

您是否已经尝试玩server_name_in_redirect

但是,我发现你通过谷歌的问题,因为我运行跟踪斜杠相同的问题。 Nginx强制一个301到相同的URL 尾随斜线。

+0

不,我没有尝试,玩......我明天 - 但看看更新请 – Serafeim

+1

只是为了避免任何浏览器缓存的副作用,我宁愿推荐测试这些重定向从壳上卷曲:“curl -IL http://correct.name.gr:8000/test/register” – vreen

+0

是的,非常好的评论... Curl FTW! – Serafeim