You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot应用部署在Nginx后重定向异常求助

解决Spring Boot + Nginx反向代理下的无限302重定向问题

我之前也碰到过一模一样的情况!Firefox提示重定向不正确、控制台刷一堆302请求,基本都是因为Spring Boot和Nginx之间的请求头配置不匹配,导致应用生成的重定向地址陷入了循环转发。结合你给出的nginx.conf片段(看起来你只贴了http块的开头,缺了关键的server配置),给你梳理下解决步骤:

1. 补全Nginx的反向代理配置

首先你需要完善Nginx的server块,确保转发请求时带上正确的头信息,告诉Spring Boot外部请求的真实协议、域名和端口:

http {
    include mime.types;
    default_type application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent"';

    # 新增或完善你的server配置
    server {
        listen 80;
        server_name your-domain.com; # 替换成你的实际域名/服务器IP

        location / {
            proxy_pass http://localhost:8080; # 指向你的Spring Boot应用端口
            # 关键:设置这些头让Spring Boot识别外部请求信息
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme; # 告诉Spring Boot请求用的是http/https
            proxy_set_header X-Forwarded-Port $server_port;
        }
    }
}

核心原因:如果没有这些头,Spring Boot会用内部的http://localhost:8080来生成重定向URL,Nginx收到这个重定向后又转发回Spring Boot,就形成了无限循环的302。

2. 配置Spring Boot信任反向代理的头

接下来需要让Spring Boot知道它运行在反向代理之后,要信任Nginx发送的X-Forwarded-*头。根据你的Spring Boot版本,修改配置文件:

如果你用的是Spring Boot 2.2+:

在application.properties中添加:

server.forward-headers-strategy=NATIVE

或者application.yml:

server:
  forward-headers-strategy: NATIVE

如果你用的是旧版本(<2.2):

server.use-forward-headers=true

或者:

server:
  use-forward-headers: true

这个配置会让Spring Boot用反向代理传来的头信息来构建外部访问的URL,而不是用自身容器的地址。

3. 检查HTTPS强制跳转的冲突

如果你配置了Nginx强制HTTPS(比如把80端口的请求跳转到443),同时Spring Boot也开启了security.require-ssl=true,一定要确保X-Forwarded-Proto头正确设置。否则Spring Boot会认为请求是HTTP,强制重定向到HTTPS,而Nginx又把这个请求转发回去,再次触发重定向。

如果用了Spring Security,还可以添加这个配置来信任转发的协议头:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requiresChannel()
                .requestMatchers(r -> r.getHeader("X-Forwarded-Proto") != null)
                .requiresSecure();
    }

    @Bean
    public ForwardedHeaderFilter forwardedHeaderFilter() {
        return new ForwardedHeaderFilter();
    }
}

最后验证步骤

  1. 重启Nginx:sudo nginx -s reload
  2. 重启Spring Boot应用
  3. 清除浏览器缓存后再访问,应该就不会出现无限302的问题了

内容的提问来源于stack exchange,提问作者Mr. Wrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:45:22