Iptables PREROUTING to redirect port 80 through varnish for selected IP

iptablesvarnish

I have installed varnish on my server and would like to test the configuration without affecting normal usage. I have apache listening on port 80 and varnish on port 8080. So, I want all requests from my IP a.b.c.d to pass through varnish and all the other IPs should be allowed to access apache normally.

I read somewhere that it is possible to use PREROUTING in Iptables to achieve this. Can some one please tell me how to do it? I have 2 sites hosted on the server, is it possible to configure this for just one domain?

Update
I tried the command, but it did not work

root@git:~# iptables -A PREROUTING -t nat -i venet0 -p tcp -s 117.201.192.67 --dport 80 -j REDIRECT --to-port 8000
root@git:~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
root@git:~# iptables -A PREROUTING -t nat -i venet0:0 -p tcp -s 117.201.192.67 --dport 80 -j REDIRECT --to-port 8000
Warning: weird character in interface `venet0:0' (No aliases, :, ! or *).
root@git:~# iptables -A PREROUTING -t nat -p tcp -s 117.201.192.67 --dport 80 -j REDIRECT --to-port 8000
root@git:~# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

I am on a VPS and do not have an interface named eth0. /sbin/ifconfig lists lo, venet0, venet0:0, venet0:1 and venet0:2 only.

Update 2 – Inserting the rule at the beginning worked

iptables -t nat -I PREROUTING -p tcp -s 117.201.192.67  --dport 80 -j REDIRECT --to-port 8000

Is it possible to check the requested hostname too? I would like to redirect only requests for mydomainname.com

Best Answer

You can specify source address (or network) in an iptables redirect as follows:

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

The rules are read from top to bottom, and first match goes, so you might have to stick it in the right place.