How to auto redirect from http to https in Apache Tomcat

Once your Tomcat is setup with a http connector on port 80 (with redirectPort=”443″) and a https connector on port 443.

Like so

    <Connector port="80" protocol="HTTP/1.1"
               maxThreads="200"
               connectionTimeout="20000"
               redirectPort="443"
               compression="on"
               compressionMinSize="2048"
               compressibleMimeType="text/html,text/xml,text/plain,text/css,application/json,application/javascript" />

    <Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="200"
               SSLEnabled="true"
               relaxedPathChars="^"
               compression="on"
               compressionMinSize="2048"
               compressibleMimeType="text/html,text/xml,text/plain,text/css,application/json,application/javascript">
        <SSLHostConfig protocols="TLSv1.2, TLSv1.3">
            <Certificate certificateKeyFile="/system/pki/privkey.pem"
                         certificateFile="/system/pki/cert.pem"
                         certificateChainFile="/system/pki/chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>

To setup an auto redirect from http to https is easy. Just add this text into your application’s web.xml file

<security-constraint>
	<web-resource-collection>
		<url-pattern>/*</url-pattern>
	</web-resource-collection>
	<user-data-constraint>
		<transport-guarantee>CONFIDENTIAL</transport-guarantee>
	</user-data-constraint>
</security-constraint>

Place this at the very end of the file.

Now whenever there is a request to http:// Tomcat will respond with a 302 redirect to https://

Leave a Reply

Your email address will not be published. Required fields are marked *