tomcat 7: automatically redirect https requests to port 8443

jon picture jon · Jul 14, 2014 · Viewed 60.3k times · Source

On tomcat7, our web application is running through https over port 8443 and works fine except that we are unable to redirect https default port (443) to 8443 so as a consequence the ':8443' has to be included in the URL whenever we have to access the application. I include some parts of our server.xml file. What should be done in order to be able to load our pages without having to enter port information in the URL?

 <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           URIEncoding="UTF-8"
           enableLookups="false"
           redirectPort="8443" />

<Connector port="80" protocol="HTTP/1.1"
           connectionTimeout="20000"
           URIEncoding="UTF-8"
           enableLookups="false"
           redirectPort="8443" />

<Connector port="443" protocol="HTTP/1.1"
           connectionTimeout="20000"
           URIEncoding="UTF-8"
           enableLookups="false"
           redirectPort="8443" />
...

<Connector port="8443"
            maxHttpHeaderSize="65536"
            scheme="https"
            secure="true"
            SSLEnabled="true"
            clientAuth="false"
            enableLookups="true"
            acceptCount="100"
            disableUploadTimeout="true"
            maxThreads="200"
            sslProtocol="TLS"
            keystoreFile="/toto/has/a/certificate.jks"
            keystorePass="totohasapassword"
            protocol="org.apache.coyote.http11.Http11NioProtocol" />

Answer

jon picture jon · Jul 14, 2014

I found a simple solution on coderanch using iptables: http://coderanch.com/t/601907/Tomcat/SSL-work

Here is the line to enter:

iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443

New edit

Here is my complete answer now. We had a problem with the previous answer as when we were calling the url from http, the redirection was ok but was always adding ':8443' at the end which was not very nice.

So in terms of iptable, here is what we wrote:

sudo iptables -t nat -I PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-ports 8080
sudo iptables -t nat -A OUTPUT -p tcp -d <your_ip_address>,<your_ip_address>  --dport 80 -j  REDIRECT --to-port 8080
sudo iptables -t nat -I PREROUTING -p tcp --destination-port 443 -j REDIRECT --to-ports 8443

Now also important is to add redirections in tomcat conf file server.xml:

<Connector port="8080"
           enableLookups="false"
           redirectPort="443" />

<Connector port="443" protocol="HTTP/1.1"
           enableLookups="false"
           redirectPort="8443" />

That's it, restart tomcat and all should be working. I'm not an expert in iptable configurations so please validate with sysadmins before modifying any existing config in production.