Tomcatの使い方 | HTTPからHTTPSへ自動リダイレクトを設定する
TomcatでHTTPアクセスされたときにHTTPSへ変更する方法について説明する。
server.xmlにSSLを設定する
Tomcatの tomcat/conf/server.xml ファイルで、HTTPS設定を443ポートに設定し、追加でHTTP設定を80ポートに設定する。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<server>
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
... 中略 ...
<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" />
... 中略 ...
</server>
web.xmlにリダイレクト設定を追加する
web.xml ファイルに次の <security-constraint> 設定を追加する。その後Tomcatを再起動し、HTTPでアクセスすると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">
... 中略 ...
<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>
web.xml ファイル内の <security-constraint> タグは複数回出現できる。Tomcatでは、セキュリティ目的で特定のHTTP Methodを制限したり、特定URLだけを設定したりする場合にも <security-constraint> を使用する。