spring boot 应用经 nginx 反向代理后,重定向 url 错误携带后端端口(如 `example.com:8080`),根本原因是 spring boot 未正确识别代理头信息,导致构建绝对 url 时误用本地监听端口。
当 Spring Boot 应用部署在反向代理(如 Nginx)之后,默认会基于 request.getServerName() 和 request.getServerPort() 构建重定向地址(例如 / → /resources/index.html 的 302 重定向)。由于应用实际监听 8080 端口,而 Nginx 仅转发请求但未显式告知“客户端是通过 http://example.com(端口 80/443)访问”,Spring Boot 便将 :8080 拼入生成的 Location 响应头中,造成 example.com:8080/resources/index.html 这类不符合预期的跳转。
关键修复:完善 Nginx 代理头,并启用 Spring Boot 的正向代理感知
✅ *第一步:补全 Nginx 配置中的关键 `X-Forwarded-头** 在location / { ... }块中添加以下三行(补充到你现有proxy_set_header` 中):
proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Proto $scheme;
完整 location 示例:
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host; # 注意:建议小写 host(兼容性更好)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://[app-ip]:8080; # 建议显式加 http:// 协议前缀
proxy_redirect off;
}⚠️ 注意事项:
推荐显式写 http://[app-ip]:8080,避免协议歧义; ✅ 第二步:确保 Spring Boot 正确信任并解析代理头
对于 Spring Boot 2.2+(推荐 2.6+),无需额外 Java 配置 —— 只需启用 server.forward-headers-strategy(默认已为 NATIVE,即自动识别标准 X-Forwarded-* 头):
# application.yml server: forward-headers-strategy: native # Spring Boot 2.2+ 默认值,可省略 port: 8080
若使用更早版本(如 2.1 或 1.x),需手动配置 TomcatServletWebServerFactory 并设置 RemoteIpValve,但现代项目强烈建议升级至受支持版本。
? 验证方式:
启动后访问 example.com/,检查浏览器 Network 面板中重定向响应(302)的 Location 头是否为 https://example.com/resources/index.html(或 http://example.com/...),不再包含 :8080。
? 补充提示:
至此,example.com/ 将干净地重定向至 example.com/resources/index.html,彻底消除 :8080 后缀问题。