Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Good people,

I have a network having the following setup

eth0 internet facing

eth1 internal network interacting with other machines within the internal network.

Id like to use this machine as a gateway with the following requirements.

  1. All traffic from the internal network going out to be SNATted with a --to through eth0
  2. Everything else to be MASQUARADed out via eth0 whose ip is

I had hoped to achieve this vis

#everything to yahoo be snatted
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to --destination 

#everything else be masqueraded
iptables --t nat --A POSTROUTING --o eth0 -j MASQUERADE

But alas the SNATting rule doesn't take a destination.

How can I achieve the above requirements?

share|improve this question

You need to put the SNAT in a new separate chain.

Then where you have the SNAT now, you need to write a rule that tests the destination IP, and if it's equvialent to the one you want to do this for, to jump to the chain you made above.

Near the beginning of your iptables file

/sbin/iptables -t nat -N SNATChain

to create a chain in the nat table called "SNATChain"

Then, replace this:

#everything to yahoo be snatted
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to --destination

with this:

#if the destination IP matches yahoo, throw it to SNATChain
/sbin/iptables -t nat -A POSTROUTING -o eth0 --destination -j SNATChain

and then populate your SNATChain with the rule you want

/sbin/iptables -t nat -A SNATChain -o eth0 -j SNAT --to

I believe that's how to do it. Been awhile since I've messed with iptables.

share|improve this answer
thanks for the prompt response. kindly provide a sample command to achieve what you have written – artfullyContrived Aug 10 '13 at 13:46
Try that out. Please note that Netfilter doesn't resolve IP addresses (above you're going to get whatever resolves to when the rules are applied), so if changes their IP address (or uses multiple in a CDN setup) you'll need to refresh the rules for it to work. – LawrenceC Aug 10 '13 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .