Tomcat - Redirecting Port 8080 to 80

Tomcat often sits behind an HTTP server such as Apache, which serves static content and proxies requests for dynamic content to Tomcat. Another popular option is to use squid as a reverse proxy. If for any reason you want Tomcat to serve all HTTP requests, you need it to listen on port 80 (and possibly 443). However, only the superuser can bind to TCP ports below 1024 on Linux, so making Tomcat listen on port 80 requires some extra work.

The easiest-to-implement solution is to simply forward incoming port 80 requests to port 8080, or whatever non-privileged port you are running Tomcat on. The Amazon Linux AMI has iptables enabled by default, but does not have any packet filtering rules defined as it apparently relies on the surrounding AWS infrastructure for security.

That said, you can go ahead and add a rule:

sudo /sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo /sbin/iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443

Check that Tomcat is running and have your browser connect to your instance without specifying a port. If you succeed, save iptables rules:

sudo /sbin/service iptables save
sudo /sbin/service iptables restart

The rules are stored in /etc/sysconfig/iptables and applied upon iptables (re)start, e.g. if you reboot the instance.

Note: The above rule applies to all packets arriving from outside to any network interface. If you are running any applications on the same instance that need to talk to Tomcat on the HTTP port, you need to add another rule.

Finally, you need the servlets inside your Web application to act as if the incoming requests were directed to port 80. This will prevent the appearance of the non-privileged port in any URLs sent back to the client. Include the proxyPort attribute in your HTTP connector config in server.xml:

<Connector port="8080" proxyPort="80" redirectPort="443" .../>
<Connector port="8443" proxyPort="443" .../>

If you want to remove iptables PREROUTING nat rules, using a following iptables command

sudo /sbin/iptables -t nat --line-numbers -L
sudo /sbin/iptables -t nat -D PREROUTING 1
sudo /sbin/service iptables save
sudo /sbin/service iptables restart


Popular posts from this blog