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

如何在Spring Boot应用中禁用302重定向 适配反向代理部署场景

方案1:修正重定向地址(推荐)

该方案无需改动原有业务逻辑,仅需让Spring Boot识别反向代理传递的请求信息,即可自动生成符合代理入口的重定向地址,不会跳转到应用本身的未开放端口。

  • 第一步:开启Spring Boot反向代理头解析
    在application.properties中添加配置:
    server.forward-headers-strategy=native
    # 可配置信任的代理IP,同机部署默认无需修改
    server.tomcat.remoteip.internal-proxies=127\\.0\\.0\\.1|::1
    
    若使用application.yml,配置如下:
    server:
      forward-headers-strategy: native
      tomcat:
        remoteip:
          internal-proxies: 127\.0\.0\.1|::1
    
  • 第二步:配置反向代理传递标准转发头
    以Nginx为例,在对应应用的location配置块中添加如下头传递规则:
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Port $server_port;
    
    若使用其他反向代理工具,配置逻辑一致,传递X-Forwarded-*系列标准头即可。
  • 补充:如果是Controller中手动返回redirect:开头的重定向地址,尽量使用相对路径,比如return "redirect:/user/list",不要写带域名端口的绝对路径。
方案2:完全禁用302重定向

适用于前后端分离等不需要服务端发起页面跳转的场景,未认证、登录/登出成功等场景直接返回状态码而非302跳转。
以下为Spring Security 6+的配置示例,5.x版本核心逻辑一致,仅部分API写法略有调整:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 其他权限配置省略
            .exceptionHandling(exception -> exception
                // 未认证时直接返回401,不跳转登录页
                .authenticationEntryPoint((request, response, authException) -> 
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED)
                )
            )
            // 禁用登录成功/失败的302跳转
            .formLogin(form -> form
                .successHandler((request, response, authentication) -> 
                    response.setStatus(HttpServletResponse.SC_OK)
                )
                .failureHandler((request, response, exception) -> 
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
                )
            )
            // 禁用登出成功的302跳转
            .logout(logout -> logout
                .logoutSuccessHandler((request, response, authentication) -> 
                    response.setStatus(HttpServletResponse.SC_OK)
                )
            );
        return http.build();
    }
}

内容的提问来源于stack exchange,提问作者Factor Three

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:06