UFW or iptables redirect (forward) to new IP

A simple steps for redirecting, forwarding or tunnelling all traffic from one host IP to another in Ubuntu.

Using UFW

Edit /etc/default/ufw to accept forwarding requests:

 DEFAULT_FORWARD_POLICY="ACCEPT" 

Edit /etc/ufw/sysctl.conf to allow IP forwarding:

net.ipv4.ip_forward=1

Edit /etc/ufw/before.rules and add the following before *filter options:

*nat
:PREROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination external_ip:8080
COMMIT 

On some configurations, MASQUERADE option needs to be enabled as well:

*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination external_ip:8080
-A POSTROUTING -j MASQUERADE
COMMIT 

Reload and commit the new rules:

ufw reload

Using iptables

Edit /etc/sysctl.conf to allow IP forwarding (add or uncomment):

net.ipv4.ip_forward=1

Save the existing rules using iptables-save:

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

Edit /etc/iptables/rules.v4 and add the following before *filter options:

*nat
:PREROUTING ACCEPT [0:0]
-A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination external_ip:8080
COMMIT 

Again, if you need to MASQUERADE, add the line before the COMMIT:

:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -j MASQUERADE

Restore the edited rules with iptables-restore:

 iptables-restore < /etc/iptables/rules.v4

To make the rules persistent on the system reboot, use iptables-persistent or custom solution with on-boot scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *