Port Redirection using IPTables

While I normally take my favorite application container and update the configuration file to listen on port 80, I’ve run into a couple of situations where this isn’t possible. The solution (and an easier one at that) is to simply use the good ol’ black art of iptables. Sacrifice a ringtail cat at a full moon and following along.

The following shows how to redirect a request to port 80 to automatically go to port 8080 without using an Apache-to-Tomcat connection or reconfiguration of a Tomcat instance.

In order to do port forwarding at the internal firewall level, delete any previous PREROUTING and OUTPUT table entries:

iptables -t nat -D PREROUTING -p tcp  --dport 80 -j REDIRECT --to-ports 8080
iptables -t nat -D OUTPUT -p tcp  --dport 80 -j REDIRECT --to-ports 8080

Of course you may want to ignore errors by appending: 2>/dev/null

Next, add the table entry:

iptables -t nat -A PREROUTING -p tcp --dport  80 -j REDIRECT --to-ports 8080
iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to-ports 8080

Note: We may need add the --destination because it should prevent a conflict with PPTP forwarding. Finally, a wee bit of magic…

iptables -t nat -L

If you have troubles, see these notes.

Other Notes

Allow port 8080 and SSH:

iptables -A tcp_inbound -p TCP -s 0/0 --destination-port 8080 -j ACCEPT
iptables -A tcp_inbound -p TCP -s 0/0 --destination-port 22 -j ACCEPT

To see what chains are in place:

iptables -L

Save any changes you’ve made to your iptables configuration, via:

iptables-save

Or write to a file:

iptables-save -c > /etc/iptables.rules

And then restore them later:

iptables-restore < /etc/iptables.rules

Remove all firewall rules and open up the world using this script:

iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

Probably want to auto generate the rules.

Date: 2011 May 6

Created: 2024-01-12 Fri 17:06