Networking – Redirect IP to another IP using iptables


I have a machine connected to a openvpn server on address My machine has an IP and it can reach the address. Once I connect to the openvpn server a new interface tun0 is created and the IP address is assigned to it. I can ping the machine hosting the VPN on IP address Traffic goes through interface tun0 as expected.

Can I set some iptables rules to force traffic to go through tun0 even if I ping directly In particular I would like to limit this only to port 80 of

Best Answer

So firstly we need to change our default route. Running ip route should show that the current default route is the gateway for the VPN network. This needs to be changed (while connected to the VPN) by removing the current default route and creating a new one pointing to your local network's gateway/router (not vpn). So if your local network gateway is you would run:

  • sudo ip route del default
  • sudo ip route default via

Now if you run ip route and route -n you should see that the new default route is now pointing to your local network and no traffic should be going through your VPN tunnel by default.

Now we can move on to redirecting all outgoing traffic on port 80/443 to your VPN's gateway.

  • sudo iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination
  • sudo iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to-destination

Now this should forward/redirect any web traffic going outbound to your VPN's default gateway/router and all other traffic to go out locally by default.

Give it a try and let me know if it achevies what you are looking for!