IPV6 nat pre-routing with iptables

Varnish is a great caching tool, but its setup isn’t that flexible when you rapidly want to switch on or off the caching. At work I use a clever solution for this: by using iptables to reroute port 80 from apache to varnish, caching can be enabled by using a simple alias-command:

alias varnishon='iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 6081;iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 6081 -j REDIRECT --to-ports 80'
alias varnishoff='iptables -t nat -D PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 6081;iptables -t nat -D PREROUTING -i eth0 -p tcp -m tcp --dport 6081 -j REDIRECT --to-ports 80'
alias varnishstatus='iptables -L -t nat |grep -q 6081; if [ "test$?" = "test0" ]; then echo "Varnish On"; else echo "Varnish Off"; fi'

varnishon routes incoming port 80 to port 6081 (the port where Varnish listens). Port 6081 also gets rerouted to port 80 (the port where Apache listens) so we can quickly bypass Varnish without accessing the server. varnishoff does exactly the opposite to disable Varnish caching.

Because I recently deployed IPV6 on the servers, I ran into troubles because ip6tables doesn’t supported nat for a while. Luckily support for this feature has been readded in kernels starting from 3.8 and iptables v1.4.18. The commands remain basically the same and can also be combined into a single alias.

alias varnishon='ip6tables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 6081;ip6tables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 6081 -j REDIRECT --to-ports 80'
alias varnishoff='ip6tables -t nat -D PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 6081;ip6tables -t nat -D PREROUTING -i eth0 -p tcp -m tcp --dport 6081 -j REDIRECT --to-ports 80'
alias varnishstatus='ip6tables -L -t nat |grep -q 6081; if [ "test$?" = "test0" ]; then echo "Varnish On"; else echo "Varnish Off"; fi
comments powered by Disqus