«

关于Nginx请求URL自动添加斜杠与端口问题

myluzh 发布于 阅读:40 Nginx


0x01 前言

最近在给客户部署K8S应用的时候遇到一个问题,就是当客户端请求的URL结尾没有斜杠时,会自动301重定向,添加反斜杠/,还会带上端口。
例如:当访问 https://pms.ccmcgc.com/contract (没有结尾斜杠)时,会自动返回 301 重定向 到 http://pms.ccmcxx.com:7081/contract/

# url最后没有加/,会自动触发一个重定向,导致访问错误。
myluzh@myluzhMacBookPro ~ % curl -I https://pms.ccmcgc.com/contract 
HTTP/2 301 
location: http://pms.ccmcxx.com:7081/contract/

# 加了/就是正常的,可以正常访问到。
curl -I https://pms.ccmcxx.com/contract/ 
HTTP/2 200 

请求路径为:客户端 -> Ingress Nginx -> Service -> Pod(前端 Nginx)

0x02 研究

这是典型的 Nginx 重定向行为不当导致的问题。Nginx 在处理目录访问时,如果访问的是一个“目录”但 URL 没有以 / 结尾,它会自动添加 / 并返回 301 重定向。
所以,Nginx 使用的是客户端请求中的 Host,但使用了本地配置的端口(比如 7081),导致重定向 URL 中包含了错误的端口号。

查阅Nginx相关的文档,找到三个和此相关的配置指令,分别为:
absolute_redirect: http://nginx.org/en/docs/http/ngx_http_core_module.html#absolute_redirect

Syntax: absolute_redirect on | off;
Default:    absolute_redirect on;
Context:    http, server, location
This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.

server_name_in_redirect: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name_in_redirect

Syntax: server_name_in_redirect on | off;
Default:    server_name_in_redirect off;
Context:    http, server, location
Enables or disables the use of the primary server name, specified by the 
server_name directive, in absolute redirects issued by nginx. When the 
use of the primary server name is disabled, the name from the “Host” 
request header field is used. If this field is not present, the IP 
address of the server is used.

port_in_redirect: http://nginx.org/en/docs/http/ngx_http_core_module.html#port_in_redirect

Syntax: port_in_redirect on | off;
Default:    port_in_redirect on;
Context:    http, server, location
Enables or disables specifying the port in absolute redirects issued 
by nginx.

absolute_redirect 是指控制跳转的url是绝对路径还是相对路径,这个指令是在 1.11.8 版本才出现。绝对路径就是刚刚上面的 https://pms.ccmcgc.com/contract ,相对路径就是 /contract 。只有在这个开关为开的时候,才会影响到后面两个指令。
server_name_in_redirect 指令是只跳转的URL的域名是用配置文件nginx.conf中的配置的 server_name ,还是用请求中获取。默认值为off,即从请求中获取。
port_in_redirect 指令是只跳转的URL的端口是用配置文件nginx.conf中的配置的 port ,还是用请求中获取。默认值为on,即配置文件定义。

0x03 解决

只需要在nginx容器配置文件 server字段里面添加以下字段,避免重定向带上错误的端口和域名。
server_name_in_redirect off:重定向的时候 会使用客户端的请求host地址,port_in_redirect off:重定向时候 不会有端口号,

# absolute_redirect on # 只有1.11.8 才支持,低版本不需要配置
server_name_in_redirect off;
port_in_redirect off;

https http k8s nginx 重定向 301


正文到此结束
版权声明:若无特殊注明,本文皆为 Myluzh Blog 原创,转载请保留文章出处。
文章内容:https://itho.cn/nginx/536.html
文章标题:《关于Nginx请求URL自动添加斜杠与端口问题