centos

Redirect port 80 to another port using iptables on CentOS

When running Node.js apps, you will typically bind your apps to another port such as 8080. However, you may not want to require users to specify a port in the endpoint

To redirect port 80 to port 8080, first open the iptables configuration file

$ vi /etc/sysconfig/iptables

You'll want to make sure that the port for your app and port 80 are both open.

-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT

Then, at the bottom of the file you'll want to setup some prerouting under network address translation.

*nat
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
COMMIT

Assuming you're doing this to a previously untouched iptables configuration file, it should look something like this when you're done:

*filter
:FORWARD ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
*nat
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
COMMIT

When you're done, save the file and restart iptables

$ service iptables restart

Now you can view localhost:8080 on localhost

more CentOS posts