Iptables redirect port 80 to port 8080

The problem:

  • You have a linux server
  • Install tomcat or any other application server
  • You don't want the application server to run as root, therefore it cannot listen to any of the ports 80 (http) or 443 (https)
  • From outside, though, the application server must be accessible on ports 80 / 443

The most popular approach:

  • Create an ordinary user specificaly for the application server (ex: tomcat)
  • Configure it to listen to a port bigger than 1024 - actually Tomcat comes by default configured to 8080 instead of 80 and 8443 instead of 443
  • Redirect the incoming connections from port 80 to 8080

The redirection is done by using the following iptables commands issued in sequence. The first one will configure the machine to accept incoming connections to port 80, the second does the same for port 8080 and the third one will do the actual rerouting. Please proceed in a similar manner for ports 443 forwarded to 8443

iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

One thing: iptables command is reserved for the root user. For any other user, the command will not be recognized. Please ensure you are root when trying to update the routing tables, also double check each command before submitting it as the impact is high.