How to redirect http to https in Tomcat

Home > Search > How-to
  by

There are two approaches to have Tomcat redirect http to https. One approach is to have Tomcat redirect every webapp from http to https. In this approach, you would add the following markup to the $CATALINA_HOME/conf/web.xml file. The other approach is to redirect certain webapps from http to https. In this approach, you would add the following markup to the $CATALINA_HOME/webapps/<web_app_name>/WEB-INF/web.xml file.

This markup must be placed inside of the <web-app> container.

<?xml version="1.0" encoding="UTF-8"?>
<web-app . . .
. . .
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>HTTPS</web-resource-name>
      <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

 

In the prior markup, CONFIDENTIAL tells Tomcat to use the redirectPort in the $CATALINA_HOME/conf/server.xml file. For example, if the Connector with port 8080 includes redirectPort to 8443, then CONFIDENTIAL will redirect from 8080 to 8443.

<Connector 
  port="8080" 
  protocol="HTTP/1.1"
  redirectPort="8443" 
/>

 

Shut down the server.

[john.doe@server1 ~]# $CATALINA_HOME/bin/shutdown.sh

 

Start the server.

[john.doe@server1 ~]# $CATALINA_HOME/bin/startup.sh

 

Ensure the server initializes.

[john.doe@server1 ~]# $CATALINA_HOME/bin/configtest.sh

 

When requesting the Tomcat application in the browser using http, the request will be redirected to https. In the screen shot below, we can see a request for http://localhost:8080 redirecs to https://localhost:8443.

 


Permit certain resources to use HTTP

If you want to permit certain resources to use HTTP, such as CSS and Images, add the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app . . .
. . .
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>HTTP</web-resource-name>
      <url-pattern>*.ico</url-pattern>
      <url-pattern>/img/*</url-pattern>
     <url-pattern>/css/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
</web-app>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments