Tomcat Usage | Configure Automatic Redirect from HTTP to HTTPS

This section explains how to redirect access from HTTP to HTTPS in Tomcat.

Configure SSL in server.xml

In Tomcat’s tomcat/conf/server.xml file, configure HTTPS on port 443 and also configure HTTP on port 80.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

... omitted ...

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

<Connector port="443" protocol="org.apache.coyote.http11.Http11Protocol"
           maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           keystoreFile="{keystoreFile}" keystorePass="{keystorePass}" />

<Connector port="8009" protocol="AJP/1.3" redirectPort="443" />

... omitted ...

</server>

Add Redirect Settings to web.xml

Add the following <security-constraint> setting to the web.xml file. Then restart Tomcat and access it through HTTP to confirm that it redirects to HTTPS.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">

    ... omitted ...

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

</web>

The <security-constraint> tag can appear multiple times in the web.xml file. Tomcat also uses <security-constraint> for security purposes, such as restricting specific HTTP methods or configuring only specific URLs.