I have an iptables rule like this:

iptables -t nat -I PREROUTING -p tcp --dport 80 -s -j DNAT --to-destination

it works perfectly.. but I want to redirect only for one URL like this:

iptables -t nat -I PREROUTING -p tcp --dport 80 -s -m string --string "google.com" -j DNAT --to-destination

which does not work in any way... please help me with this

2 Answers 2


That won't work. Only the first packet of every connection cross the NAT table. The strings only will be visible in the third packet, the one with the payload.

You should use a proxy to do that, in transparent mode if you don't want to configure it in the browsers.


Those rules do the same thing. Regardless of which one matches, the result is the same.

Any packet that could match the second rule would already have matched the first rule. Even if a packet did match the second rule, it doesn't do anything different to the first rule. (Actually, Iain correctly pointed out the -I in your rules, meaning that the rules are in fact in the opposite order.)

I ought to warn you that trying to change packet flows the way you are doing won't work like you expect. IPTables works at the packet level, not the connection level. A rule with --string "google.com" would match the packet(s) on this page that contain the string "google.com" but not any part of the TCP handshake and not any of the other packets that don't contain "google.com". This page is currently about 45KB which would be about 30 packets and only two of them would match. A rule with --string "google.com" probably wouldn't match any packets from Google's actual home page. It might redirect DNS requests if the happen to be done over TCP.

As @diegows pointed out in his answer, only the first packet of any TCP connection traverses through the nat table because you can't redirect packets in the middle of a TCP connection and expect it to work so they don't make it possible. Even if you put this kind of rule in a different table, it still won't work.

  • He's using -I so the second rule will end up being the first ;)
    – user9517
    Jun 27, 2012 at 22:07
  • Ah yes. Well, most of my answer is still correct. :-P
    – Ladadadada
    Jun 27, 2012 at 22:32
  • The second rule will never match. Have a look at my answer. Jun 28, 2012 at 12:37

You must log in to answer this question.

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