Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have an iptables rule like this:

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

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

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

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

share|improve this question

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.

share|improve this answer

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.

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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