当主机端口!=容器端口时,Nginx会在docker机器上重写

我试图运行多个docker容器运行nginx监听端口80,但不同的主机端口映射到容器端口80。

大多数情况下,这是有效的,除了当nginx由于缺less一个结尾的斜杠做redirect。

server { listen 80; root /var/www; index index.html; location /docs {} } 

鉴于上述nginxconfiguration和一个docker容器运行它与主机端口8080映射到容器端口80我可以得到本地主机:8080 /文档/通过curl好了:

 > GET /docs/ HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 200 OK * Server nginx/1.9.5 is not blacklisted < Server: nginx/1.9.5 < Date: Sat, 28 Nov 2015 17:27:05 GMT < Content-Type: text/html < Content-Length: 6431 < Last-Modified: Sat, 28 Nov 2015 17:17:06 GMT < Connection: keep-alive < ETag: "5659e192-191f" < Accept-Ranges: bytes < ... html page ... 

但如果我请localhost:8080 / docs我得到一个redirect到本地主机/ docs /

 > GET /docs HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 301 Moved Permanently * Server nginx/1.9.5 is not blacklisted < Server: nginx/1.9.5 < Date: Sat, 28 Nov 2015 17:29:40 GMT < Content-Type: text/html < Content-Length: 184 < Location: http://localhost/docs/ < Connection: keep-alive < ... html redirect page ... 

如何在redirect时让nginx保留原始端口? 我试着看着port_in_redirect和server_name_in_redirect,但他们没有帮助。


编辑

基于https://forum.nginx.org/read.php?2,261216,261216#msg-261216现在看起来不太可能。

最简单的解决scheme是删除index指令,而不是依赖显式或隐式$uri/ redirects。 例如:

 server { listen 80; root /var/www; location /docs { try_files $uri $uri/index.html =404; } } 

这不是完全相同的行为,因为它完全避免了redirect。 如果您想要索引模块提供的尾部斜线redirect,则需要更复杂的解决scheme。 例如:

 server { listen 80; root /var/www; location /docs { try_files $uri @redirect; } location @redirect { if ($uri ~* ^(.+)/$) { rewrite ^ $uri/index.html last; } if (-d $document_root$uri) { return $scheme://$host:8080$uri/; } return 404; } } 

HTTP客户端将把端口放在主机头中。 如果在执行redirect时使用主机标头的原始值,则应该按预期工作。 我testing了下面的代码,看起来正在做你所要求的:

 location ~ ^.*[^/]$ { try_files $uri @rewrite; } location @rewrite { return 302 $scheme://$http_host$uri/; } 

 > GET /bla HTTP/1.1 > User-Agent: curl/7.29.0 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 302 Moved Temporarily < Server: nginx/1.9.7 < Date: Sun, 29 Nov 2015 06:23:35 GMT < Content-Type: text/html < Content-Length: 160 < Connection: keep-alive < Location: http://localhost:8080/bla/