Redirecting network traffic to a new IP using iptables

Login to the old server as root and enter the following

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp -dport 80 -j DNAT –to-destination 1.2.3.4:80
iptables -t nat -A POSTROUTING -j MASQUERADE

Here the new ip address is 1.2.3.4. Now all the traffic to port 80 will get redirected to port 80 of 1.2.3.4.

(assuming that you do not have other iptables rules blocking access to port 80 )

If you want to redirect traffic to other ports such as for email POP, IMAP, or SSL , you can simply add in additional iptables rules.

For example to have POP3 redirection, you can add in an additional rule like this:

iptables -t nat -A PREROUTING -p tcp –dport 110 -j DNAT –to-destination 1.2.3.4:110

You may find this helpful while server migration

Advertisements

Tags:

6 Responses to “Redirecting network traffic to a new IP using iptables”

  1. fakir Says:

    hi,

    tried this on RHEL 5.6 and Centos 5.6 and this does not work. 😦
    what OS are you trying ?

    Regards

  2. Josh Says:

    iptables -t nat -A POSTROUTING -j MASQUERADE

    gives the following:-

    iptables: No chain/target/match by that name.

    • David Svarrer Says:

      You just need to add that chain… Your system is surely not having the POSTROUTING or even PREROUTING chain…. Now, time for you to do some home work:

      Use man iptables command, and look for how to add a chain (or create a chain)… That is also an iptables-command, so hereby a little home work for you 🙂

  3. .htaccess 301 Redirect | Hello, IT. Says:

    […] 2- En un servidor Linux, modificar iptables para redirigir todo el tráfico HTTP al nuevo servidor. Aquí las instrucciones. […]

  4. thisistyson Says:

    Great! Exactly what I was looking for… so much useless information on the web, glad I finally found this.

  5. shahroz Says:

    Hello thank you for an amazing tutorial.

    I have a question and that is

    Is it possible to use more than 1 ip address.

    In my scenario if i redirect 1 example.com at 1.1.1.1 and now 1.1.1.1 using your above technique redirect my example.com 2.2.2.2

    Now if my another domain domain2.com is also at 1.1.1.1 and now i want it redirect to 3.3.3.3 so how is this possible using 1 ip address?

    I mean 1.1.1.1 redirect example.com to 2.2.2.2 and doamain.com to 3.3.3.3

    Please tell me it’s solution i searched on google and spend alot of time but didnot find any solution so please help me.

    With Best Regards

    Shahroz

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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


%d bloggers like this: