In this post, we will learn how to redirect a request from port 80 to some other port using iptables in CentOS.
Why to Redirect 80 Port?
Mostly Web applications made in Node.js, java and many others have a default port on which the web application runs. For example, Node.js and Java tomcat server have 8080 as their default port. But Website HTTP requests works on 80 port. So there is a need to redirect port from 80 to 8080.
To Redirect Port 80 to port 8080 in CentOS, you need to follow below steps:
- Open the iptables configuration file using terminal:
$ vi /etc/sysconfig/iptables
- Now make both port 80 and port 8080 Open for accepting:
-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
- Now at the bottom of the iptables file setup some prerouting under Network Address Translation(NAT):
*nat
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
COMMIT
- Once you are done with above steps, your file should look something like this:
*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 7822 -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
- Now save the file by pressing ESC key and then type ":wq", After this your file will be saved.
- Now restart iptables:
$ service iptables restart
You can now view your Web Application (originally hosted on http://localhost:8080) on http://localhost