Spring Boot开发环境:如何禁用HSTS头解决OPTIONS请求307重定向失败问题
解决Spring Boot发送HSTS头导致的OPTIONS重定向问题
嘿,这个问题我太熟了——Yandex浏览器(基于Chromium内核)会严格遵守HSTS头的规则,强制把HTTP请求重定向到HTTPS,而你开发环境没配置SSL证书,预检的OPTIONS请求被307重定向后自然就报错了。核心解决思路就是让Spring Boot停止发送HSTS响应头,下面给你几种靠谱的实现方式:
方法1:通过配置文件全局禁用(最简单)
直接在你的application.properties或者application.yml里添加配置,一步到位:
用properties格式:
server.http.hsts.enabled=false
用yml格式:
server: http: hsts: enabled: false
这个配置会让Spring Boot内置的服务器(Tomcat、Jetty等)不再自动添加HSTS头,是最省心的方案。
方法2:Java代码自定义服务器配置(更灵活)
如果需要更细粒度的控制,或者配置文件方式没生效,可以写一个配置类来修改服务器设置:
import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ServerHstsConfig { @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> disableHstsHeader() { // 清空HSTS相关配置,彻底禁用头信息 return factory -> factory.setHttpStrictTransportSecurity(null); } }
方法3:如果用了Spring Security,额外关闭Security的HSTS设置
很多项目会搭配Spring Security使用,而Security默认也会添加HSTS头,这时候只改服务器配置可能不够,得在Security配置里也禁用:
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 这里保留你原有的其他Security配置,比如授权、CORS等 .headers() .httpStrictTransportSecurity().disable(); // 禁用Security的HSTS头 } }
最后一步:清除浏览器的HSTS缓存
改完配置重启应用后,别忘了清除浏览器里已缓存的HSTS规则——Yandex浏览器可以访问chrome://net-internals/#hsts(因为它基于Chromium),在「Delete domain security policies」里输入你的本地开发域名(比如localhost或者自定义的域名),点击删除,这样浏览器就不会再强制跳HTTPS了。
内容的提问来源于stack exchange,提问作者Leukipp
相关产品推荐
相关产品推荐

