在Apache Tomcat中执行301重定向从http到https

use*_*806 11 apache ssl tomcat

我在我的Web应用程序中配置了SSL.我已根据所需步骤在我的Tomcat中安装了证书.

我一直关注的教程是 https://www.mulesoft.com/tcat/tomcat-security

我强制使用https over http,这意味着任何对http的请求都将转发到https.我在server.xml中进行了以下更改

<Connector port="8080" protocol="HTTP/1.1" 

           connectionTimeout="20000" 

           redirectPort="443"

           proxyHost="10.1.1.1" proxyPort="80"

           URIEncoding="UTF-8"

           maxHttpHeaderSize="32768"/>
Run Code Online (Sandbox Code Playgroud)

web.xml更改如下:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>SecureConnection</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
Run Code Online (Sandbox Code Playgroud)

但是,正在发生的重定向是临时重定向,即302.我想使用301重定向,即永久重定向.

我怎样才能做到这一点?

Dan*_*usa 5

这是在您的 Realm 上配置的。查看transportGuaranteeRedirectStatus您的特定 Realm 实现的属性。

https://tomcat.apache.org/tomcat-8.5-doc/config/realm.html

例如:server.xml 有这个开箱即用的

  <Realm className="org.apache.catalina.realm.LockOutRealm">
    <!-- This Realm uses the UserDatabase configured in the global JNDI
         resources under the key "UserDatabase".  Any edits
         that are performed against this UserDatabase are immediately
         available for use by the Realm.  -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase"/>
  </Realm>
Run Code Online (Sandbox Code Playgroud)

它没有设置,transportGuaranteeRedirectStatus所以默认为 302。如果你想让它使用 301,只需将该属性添加transportGuaranteeRedirectStatus="301"到顶级领域(根据你的配置,你可能没有嵌套领域)并重新启动 Tomcat。

前任:

  <Realm className="org.apache.catalina.realm.LockOutRealm" transportGuaranteeRedirectStatus="301">
    <!-- This Realm uses the UserDatabase configured in the global JNDI
         resources under the key "UserDatabase".  Any edits
         that are performed against this UserDatabase are immediately
         available for use by the Realm.  -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase" />
  </Realm>
Run Code Online (Sandbox Code Playgroud)

如果您的配置中没有定义 Realm 标记,Tomcat 将默认使用NullRealm。如果您想在这种情况下覆盖重定向,您只需要在其下定义一个 NullRealm,并transportGuaranteeRedirectStatus在其上设置属性。

希望有帮助!