Port redirection (also known as port forwarding) is a useful technique for redirecting traffic from one port to another on a Linux system using the iptables
firewall. Here’s an example of how to set up port redirection using iptables
.
Let’s say you have a web server running on port 8080, but you want to make it available on the default HTTP port (port 80) instead. You can use the following iptables
rules to redirect traffic from port 80 to port 8080:
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -A INPUT -p tcp -m state --state NEW --dport 8080 -i eth0 -j ACCEPT
These rules do the following:
- The first rule (
iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
) adds a rule to thePREROUTING
chain in thenat
table. This rule matches incoming traffic on port 80 (--dport 80
) and redirects it to port 8080 (--to-port 8080
), which is where your web server is actually listening. The-i eth0
option specifies that the rule should only apply to incoming traffic on theeth0
network interface. - The second rule (
iptables -A INPUT -p tcp -m state --state NEW --dport 8080 -i eth0 -j ACCEPT
) adds a rule to theINPUT
chain in thefilter
table. This rule allows incoming traffic on port 8080 (--dport 8080
) that is part of a new connection (-m state --state NEW
) and is coming in on theeth0
network interface (-i eth0
). This rule is necessary to allow the redirected traffic to actually reach your web server.
Note that these rules assume that your web server is running on the same machine as the iptables
firewall, and that it is listening on port 8080. If your web server is running on a different machine or is listening on a different port, you’ll need to adjust the rules accordingly.