【发布时间】:2017-02-04 04:26:29
【问题描述】:
使用 Spring Boot 和/或底层 Tomcat 连接器,我希望使用 301 重定向而不是 302 将所有 HTTP 请求重定向到 HTTPS。我目前有一个完全按照我想要的方式工作的解决方案,只是它返回 302s 而不是 301s。这是它的样子:
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(createHttpConnector());
return tomcat;
}
private Connector createHttpConnector() {
Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setSecure(false);
connector.setPort(80);
connector.setRedirectPort(443);
return connector;
}
(我的默认连接器是 HTTPS,在 application.properties 中定义,正如我之前在整个互联网中看到的那样。)
我需要返回 301,因为我以前没有 HTTPS 选项,但现在我有(而且这是强制性的)并且该选项使用 HTML5 application caching,如果用户离线并尝试访问 HTTP URL;据我了解,Chrome 等浏览器不会缓存 302 重定向,但 do 会缓存 301,因此即使请求 HTTP 而不是 HTTPS,切换到始终返回 301 也应该使网站可以离线使用,就像旧书签或延迟链接到我的 .com 地址而不指定协议的情况一样。
This SO question 确实得到了我正在寻找的东西,但它没有答案并且是 Tomcat 特定的;如果有任何特定于 Spring 或 Spring Boot 的东西可以用来实现这一点,我也对此持开放态度。例如,我目前没有使用 Spring Security,但如有必要,我愿意将其加入其中。
有什么想法吗?提前感谢您的帮助。
【问题讨论】:
标签: java spring tomcat spring-security spring-boot