Redirect one port to another port using iptables

You can easily redirect incoming traffic by inserting rules into PREROUTING chain of the nat table. You can set destination port using the REDIRECT target.

IPTables

IPTables

Following is the procedure:
Use the following for redirecting TCP traffic from one SRC_PORT to DEST_PORT:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport SRC_PORT -j REDIRECT --to-port DEST_PORT

Use the following for redirecting UDP traffic from one SRC_PORT to DEST_PORT:

iptables -t nat -A PREROUTING -i eth0 -p udp --dport SRC_PORT -j REDIRECT --to-port DEST_PORT

Use the following for redirecting TCP traffic from one IP:SRC_PORT to another IP:DEST_PORT:

iptables -t nat -I PREROUTING --src SRC_IP --dst DEST_IP -p tcp --dport SRC_PORT -j REDIRECT --to-ports DEST_PORT

Now verify the rule that we just added by:

iptables -t nat -Lnv

You can see the the rule(s) that you have added earlier in the list. Now time to save the rules.

Here, if you just want these redirection rules to persist only for current boot then just run the following command.

iptables-save 

If you want the redirection rules to persist even after the reboot then, please follow the procedure below: (Ubuntu 14.04)

sudo iptables-save > /etc/network/interfaces.d/iptables.rules
echo "post-up iptables-restore < /etc/network/interfaces.d/iptables.rules" > /etc/network/interfaces.d/eth0.cfg

Leave a Reply