How-To: Redirecting network traffic to a new IP using IPtables

While doing a server migration, it happens that some traffic still go to the old machine because the DNS servers are not yet synced or simply because some people are using the IP address instead of the domain name….

By using iptables and its masquerade feature, it is possible to forward all traffic to the old server to the new IP.

This tutorial will show which command lines are required to make this possible.

In this article, it is assumed that you do not have iptables running, or at least no nat table rules for chain PREROUTING and POSTROUTING.

The first thing to do is do enable IP forwarding. This is done either by using:

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


# sysctl net.ipv4.ip_forward=1

Then, we will add a rule telling to forward the traffic on port 1111 to ip on port 1111:

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

and finally, we ask IPtables to masquerade:

iptables -t nat -A POSTROUTING -j MASQUERADE

Optionally, you could only redirect the traffic from a specific source/network with, for a host only:

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

or for a whole network

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

that’s it, now the traffic to port 1111 will be redirected to IP .
If you go on host, you should see a lot of traffic coming from the host doing the redirection.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s