Spring Boot / Tomcat:HTTP - > HTTPS 301重定向

时间:2016-09-26 17:59:48

标签: java spring tomcat spring-security spring-boot

使用Spring Boot和/或底层Tomcat连接器,我希望使用301重定向将所有HTTP请求重定向到HTTPS,而不是302。我目前有一个完全按照我想要的方式工作的解决方案,除了它返回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重定向,但执行缓存301s,因此即使向HTTP而不是HTTPS发出请求,切换到返回301s也应该使网站可以脱机使用,就像旧书签或延迟链接到我的.com地址而没有指定协议一样。

This SO question确实得到了我正在寻找的东西,但它没有得到答案,而且特定于Tomcat;如果我可以利用Spring或Spring Boot特有的任何东西来实现这一目标,我也会对此持开放态度。例如,我目前没有使用Spring Security,但如果有必要的话,我愿意把它扔进混合中。

有什么想法吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

自从我最初发布此问题以来已经过了一年多,但我只是将this commentthis comment拼凑到其他SO问题上以获得301重定向。这是我想出的内容,重点是addContextCustomizers位:

@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());
    tomcat.addContextCustomizers((TomcatContextCustomizer) context -> {
        NullRealm realm = new NullRealm();
        realm.setTransportGuaranteeRedirectStatus(301);
        context.setRealm(realm);
    });
    return tomcat;
}

不幸的是,仅凭这一点似乎并没有解决HTML5应用程序缓存问题,但我会继续深入研究这方面的问题。不管怎样,又过了一年......

相关问题