IP using iptables to redirect from a country to a predetermined page
Yesterday there was a client who wants his website to block all IP from China and from China to visit redirected to a predetermined page (or site)。Orthodox approach should be used apache + mod_geoip or nginx + http_geoip_module do,But I found that the customers use the apache / directAdmin / suexec,suexec and seems to have a problem with mod_geoip,VPSee do not want to move a large client configuration,We intend to use iptables to implement this requirement。The idea is that,Using iptables to all traffic from China to guide site 81 port,And start listening on port 81 on apache,Put a predetermined page (or site)。
First IPdeny Download to country code-programmed list of IP addresses,Such as downloading cn.zone:
# wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone
After obtaining all the required IP addresses,Read cn.zone file with the following script line by line and added to the iptables:
#!/bin/bash # Redirect traffic from a specific country to a specific page # written by vpsee.com COUNTRY="cn" YOURIP="1.2.3.4" if [ "$(id -u)" != "0" ]; then echo "you must be root" 1>&2 exit 1 fi iptables -F iptables -X iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT iptables -A INPUT -i eth0 -j ACCEPT iptables -A OUTPUT -o eth0 -j ACCEPT # Redirect incoming http (80) from China to 81 for c in $COUNTRY do country_file=$c.zone IPS=$(egrep -v "^#|^$" $country_file) for ip in $IPS do echo "redirecting $ip" iptables -t nat -I PREROUTING -p tcp --dport 80 -s $ip -j DNAT \ --to-destination $YOURIP:81 done done iptables-save > /etc/sysconfig/iptables chmod go-r /etc/sysconfig/iptables service iptables restart
After this IP from China YOURIP visit the site will be automatically redirected to YOURIP:81 This port,We then modify the apache configuration,Add a Listen 81 DocumentRoot and well placed inside a predetermined page (or site) will be able to