port_in_redirect仅控制nginx自身生成的重定向中location头是否含端口,不影响后端返回的跳转;https下设为off可避免暴露内部非标端口,后端跳转需用proxy_redirect单独处理。

port_in_redirect 控制的是 Nginx 自己生成重定向响应时 Location 头里是否带端口,它不处理后端返回的跳转——后者得靠 proxy_redirect。在 HTTPS 场景下,用户访问的是 443 端口(或经由 80 转发的 HTTPS),但 Nginx 若监听非标端口(比如 8443)或被前置设备(F5、CDN、防火墙)代理,就容易把内部端口暴露进跳转地址,导致浏览器跳到 https://example.com:8443/login 这类不可达链接。关键不是“要不要端口”,而是“要哪个端口”:对外应始终用标准端口(443 不显式写出),对内不能泄露真实监听端口。
port_in_redirect 的实际作用范围
它只影响 Nginx 主动发起的重定向,例如:
return 302 /new;rewrite ^/old(.*)$ /new$1 redirect;- 内部路径匹配失败且配置了
error_page 404 =302 /fallback
它完全不干预后端应用(如 Spring Boot、Django、Tomcat)返回的 301/302 响应。那些 Location 头由后端拼接,Nginx 默认原样转发。所以即使你把 port_in_redirect 设为 off,后端跳转仍可能带错端口或协议。
HTTPS 下设为 off 是常见且安全的选择
当用户通过 HTTPS(443)访问,而 Nginx 监听的是 443 或被反向代理到 443 时,设 port_in_redirect off; 可确保 Nginx 自己的跳转地址干净简洁:
- 请求是
https://example.com:443/login→ 跳转成https://example.com/dashboard(省略 443,符合 HTTP 规范) - 请求是
https://example.com:8443/admin(调试用)→ 跳转仍为https://example.com/dashboard(不暴露 8443)
注意:off 不代表强制写 80 或 443,而是让 Nginx 忽略当前监听端口,改用请求中的 $scheme 和 $host 拼接,而标准端口在 URL 中本就不显示。
后端跳转问题必须用 proxy_redirect 单独解决
如果后端返回了 Location: http://example.com:8080/callback 或 Location: https://backend.local:8443/auth,你需要在 proxy_pass 所在 location 块中配置:
-
proxy_redirect http:// $scheme://;—— 把后端的 http 强制转为当前请求协议(http→http,https→https) -
proxy_redirect https:// $scheme://;—— 防止后端硬编码 https 却没走 TLS 终结 -
proxy_redirect ~^http://[^/]+(/.*)$ $scheme://$host$1;—— 更稳妥地剥离原始 host 和端口,统一补上前置域名
同时建议配合 proxy_set_header Host $host;(不要带 $server_port),避免后端误读端口再生成错误跳转。
别和 server_name_in_redirect 搞混
server_name_in_redirect off; 影响的是跳转地址里的 host 部分:设为 off 时,Nginx 用服务器 IP 替代 $server_name;设为 on(默认)才优先用配置的 server_name 或请求头 Host。它和端口无关,但在 HTTPS 场景中常与 port_in_redirect 同时调整,确保整个跳转 URL(协议 + host + path)对外一致可信。











