Http to Https redirect on Tomcat

This post assumes that:

  • You have bought the SSL
  • Have successfully installed it on Tomcat with Keytool

Now you are trying to figure out how to automatically redirect http to https.

You will need to edit two files under Tomcat configuration: server.xml and web.xml. Then restart tomcat to reflect the changes.

Step 1:

Open server.xml and find

<Connector port="80" protocol="HTTP/1.1"
 connectionTimeout="20000"
 redirectPort="8443" />

Change to

<Connector port="80" protocol="HTTP/1.1"
 connectionTimeout="20000"
 redirectPort="443" />

And make sure you have these lines as well. Change KeystoreFile and KeystorePass according to your details

<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
 maxThreads="150" scheme="https" secure="true"
 keystoreFile="/home/server/cert/cert.tomcat.jks"
 keystorePass="certificatename" clientAuth="false" sslProtocol="TLS">
</Connector>

Step 2:

Open web.xml ( not the one under tomcat/conf/web.xml but where your site folder is something like /site-folder/WEB-INF/conf/web.xml) and add these lines before the ending </web-apps> tag.

<security-constraint>
 <web-resource-collection>
 <web-resource-name>Protected Context</web-resource-name>
 <url-pattern>/*</url-pattern>
 </web-resource-collection>
 <!-- auth-constraint goes here if you require authentication -->
 <user-data-constraint>
 <transport-guarantee>CONFIDENTIAL</transport-guarantee>
 </user-data-constraint>
</security-constraint>

Now restart the tomcat and all pages should redirect to https