我正在尝试运行多个 docker 容器,所有 docker 容器都运行 nginx 侦听端口 80,但不同的主机端口映射到容器端口 80。
在大多数情况下,这是有效的,除非 nginx 由于缺少尾部斜杠而进行重定向。
server {
listen 80;
root /var/www;
index index.html;
location /docs {}
}
Run Code Online (Sandbox Code Playgroud)
鉴于上述 nginx 配置和运行它的 docker 容器,主机端口 8080 映射到容器端口 80,我可以通过 curl ok 获取 localhost:8080/docs/ :
> 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 ...
Run Code Online (Sandbox Code Playgroud)
但是如果我请求 localhost:8080/docs 我会重定向到 localhost/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 ...
Run Code Online (Sandbox Code Playgroud)
进行重定向时如何让 nginx 保留原始端口?我试过查看 port_in_redirect 和 server_name_in_redirect 但它们没有帮助。
编辑
基于https://forum.nginx.org/read.php?2,261216,261216#msg-261216这现在看起来不可能。
HTTP 客户端会将端口放在 Host 标头中。如果在执行重定向时使用主机标头的原始值,它应该会按预期工作。我测试了以下代码,看起来完全符合您的要求:
location ~ ^.*[^/]$ {
try_files $uri @rewrite;
}
location @rewrite {
return 302 $scheme://$http_host$uri/;
}
Run Code Online (Sandbox Code Playgroud)
> 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/
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案是删除index
指令,而不是依赖显式或隐式$uri/
重定向。例如:
server {
listen 80;
root /var/www;
location /docs {
try_files $uri $uri/index.html =404;
}
}
Run Code Online (Sandbox Code Playgroud)
这不是完全相同的行为,因为它完全避免了重定向。如果您想要像 index 模块提供的尾部斜杠重定向,则需要更复杂的解决方案。例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11875 次 |
最近记录: |