Spring Boot中根据server.ssl.enabled条件重定向至HTTPS
解决方案
你可以通过读取server.ssl.enabled配置项,动态决定是否添加强制HTTPS的规则,具体实现如下:
方式一:通过@Value注入配置
先注入server.ssl.enabled的配置值(默认设为false,避免未配置时出错):
@Value("${server.ssl.enabled:false}") private boolean sslEnabled;
然后修改SecurityFilterChain的构建逻辑,仅当SSL启用时添加强制HTTPS规则:
@Bean SecurityFilterChain getSecurityFilterChain(HttpSecurity httpSecurity) throws Exception { if (sslEnabled) { httpSecurity.requiresChannel(crmr -> crmr.anyRequest().requiresSecure()); } return httpSecurity.authorizeRequests(eir -> eir.anyRequest().permitAll()) .csrf(AbstractHttpConfigurer::disable) .build(); }
方式二:通过Environment获取配置
也可以直接在Bean方法中注入Environment来读取配置,无需额外成员变量:
@Bean SecurityFilterChain getSecurityFilterChain(HttpSecurity httpSecurity, Environment env) throws Exception { boolean sslEnabled = Boolean.parseBoolean(env.getProperty("server.ssl.enabled", "false")); if (sslEnabled) { httpSecurity.requiresChannel(crmr -> crmr.anyRequest().requiresSecure()); } return httpSecurity.authorizeRequests(eir -> eir.anyRequest().permitAll()) .csrf(AbstractHttpConfigurer::disable) .build(); }
逻辑说明
- 当
server.ssl.enabled=true时,保留原有的强制HTTPS重定向规则; - 当
server.ssl.enabled=false时,跳过该规则,允许请求通过HTTP访问。
内容的提问来源于stack exchange,提问作者KirEvse
相关产品推荐
相关产品推荐

