How can I make iptables NAT all packets, except those, that have a target address from subnet?


If I understand you well, this should be fairly easy using the option -d with negation. For example, a rule like this one:

$ iptables -A POSTROUTING ! -d -j SNAT --to-source new_source_ip

Of course, you can change the rule according to your needs. This changes the source IP of all packets destined to any destination except the indicated subnet.


In my opinion following order of iptables commands would work:

1. iptables -t nat -A POSTROUTING -s -o eth0 -j RETURN
2. iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE

rule 1 will match your network and won't MASQUERADE it rule 2 will masquerade all but generally it's not good idea to give wildcard (I'm not even sure if it will work). You should selectively add all networks that you want to masquerade and rest just won't be masqueraded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.