How to Redirect Traffic to Another Computer (IP) in Linux

This tutorial explains you how to redirect Internet traffic from one computer running Linux to another IP address.

If you have ever handled the migration of a web service or a website from one server to another you know how crazy the experience can be. However, if you break the process up into clear steps and run constant checks you can make the experience a little easier on yourself. One of the problems that you might run into towards the end of the migration is the period when you have the website running well on the new location but need to wait for the domain name to be forwarded to the new server. You can either shut down your service till the domain is done forwarding, or you can setup your first server to forward all its traffic to the new server. Let’s take a look at how you can do that on a Linux machine using IPTables.

In case you didn’t already know, IPtables is a software firewall that ships with most distributions of Linux. It is an extremely useful software and can be used for a lot more than just as a firewall. In this exercise we will configure IPTables on a Linux server to redirect all the traffic coming on port 80, (which is the default web server port), to a server with the IP The first step is to set your Linux box to allow this kind of forwarding to take place. Open a terminal window, log in as root user and run the following command:

# echo 1 >/proc/sys/net/ipv4/ip_forward

The next step is to tell IPTables to redirect the traffic to the new server:

# iptables -t nat -A PREROUTING -p tcp –dport 80 -j DNAT –to-destination

Here’s where the IPTables magic happens. With the third and final step we tell IPTables to rewrite the origin of connections to the new server’s port 80 to appear to come from the old server.

# iptables -t nat -A POSTROUTING -p tcp -d –dport 80 -j MASQUERADE

The final step is required because if we don’t tell the web server of the new server that the connections are coming from the client machines, it would think that they are originating from the old server.

If this article helped you, I'd be grateful if you could share it on your preferred social network - it helps me a lot. If you're feeling particularly generous, you could buy me a coffee and I'd be super grateful :)

buy a coffee for

Home » Linux » How to Redirect Traffic to Another Computer (IP) in Linux

3 thoughts on “How to Redirect Traffic to Another Computer (IP) in Linux”

  1. Here’s the correct one for Debian:

    iptables -t nat -A PREROUTING -p tcp –dport 80 -j DNAT –to-destination

    iptables -t nat -A POSTROUTING -p tcp -d –dport 80 -j MASQUERADE

  2. Great!!
    Also you can change destination port using (in step 2):

Leave a Comment

Your email address will not be published.