
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;
}⚠️ 注意事项:
- Host 头应设为 $http_host(保留原始 Host,含端口信息由代理控制),而非 $host(会丢失端口,影响 HTTPS 判断);
- proxy_pass 推荐显式写 http://[app-ip]:8080,避免协议歧义;
- proxy_redirect off 是必要的,防止 Nginx 自动重写重定向响应头(该任务应交由 Spring Boot 完成)。
✅ 第二步:确保 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。
? 补充提示:
- 若启用 HTTPS,Nginx 中 X-Forwarded-Proto 必须设为 $scheme(自动匹配 http/https),否则 Spring Boot 可能生成 http:// 开头的跳转链接;
- X-Forwarded-Port 确保 Spring Boot 在生成绝对 URL 时使用客户端访问端口(80/443),而非服务端口(8080);
- 所有 X-Forwarded-* 头必须由可信代理(Nginx)设置,切勿允许客户端伪造,生产环境应在防火墙/Nginx 层过滤外部传入的这些头。
至此,example.com/ 将干净地重定向至 example.com/resources/index.html,彻底消除 :8080 后缀问题。










