用 iptables 把来自某个国家的 IP 重定向到预定页面
昨天有位客户想在他网站上阻止所有来自中国的 IP 并且把来自中国的访问重定向到某个预定的页面(或网站)。正统的做法应该是用 apache + mod_geoip 或者 nginx + http_geoip_module 来做,但是发现这位客户使用了 apache/directAdmin/suexec,suexec 好像和 mod_geoip 在一起有问题,VPSee 不想大动客户的配置,所以打算用 iptables 来实现这个要求。想法是这样的,用 iptables 把来自中国的流量全部导向到网站的 81 端口,并在 apache 上启动监听81端口,放上预定的页面(或网站)。 
先到 IPdeny 下载以国家代码编制好的 IP 地址列表,比如下载 cn.zone: 
# wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone 
得到需要的所有 IP 地址后,用下面的脚本逐行读取 cn.zone 文件并加入到 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 
这样来自中国的 IP 访问 YOURIP 这个网站后就会自动导向到 YOURIP:81 这个端口,然后我们修改 apache 的配置,增加一个 Listen 81 和 以及在 DocumentRoot 里面放上预定的页面(或网站)就可以了 |