There are many friends who have built foreign trade websites who want to restrict their websites from being accessed by domestic IPs. There are also some friends whose websites store resources that need to be blocked from specific IPs for various reasons. Some friends have seen attacks. Most of the source IPs come from abroad, and you want to prevent foreign IPs from accessing the website.

No matter what the reason is, blocking and blocking IP access from specific regions and countries are often used in our daily website building. If you are using PHP, a relatively simple method is to add the code to determine the IP in the PHP file and use the IP library for comparison. If the IP is within the restricted access range, prevent it from continuing to access.

If the website is Nginx, you can directly use the Nginx-ngx_http_geoip_module module. This module can be accurate to the IP of the country, province, city, etc., and all identification and blocking of access are performed by Nginx, so it is more resource-saving compared to PHP. But Nginx is more troublesome to compile.

If the website is built on a VPS or independent server, you can use Linux firewall directly and use iptables rules to block IP access from specific countries and provinces. Of course, WordPress users don’t have to worry about Nginx, iptables and other configuration issues, because WordPress already has various plug-ins that restrict IP access.

This article will share four ways to set up websites to block and block IP access from specific regions and countries: PHP code, Nginx module, iptables firewall and WordPress plug-in. If you are always troubled by various malicious attacks during the website construction process, you can try the following methods:

  1. Five security tips for using a free VPS control panel – don’t let hackers take advantage
  2. How to enable Nginx fastcgi_cache cache acceleration in WordPress - Nginx configuration example
  3. Ten CloudFlare Free CDN Acceleration Tips You May Not Know-SSLDDOSCache

PS: Updated on March 25, 2019, Regarding the security issues of VPS, many friends may ignore the SSH configuration of the VPS itself. Here are the strengthening strategies: VPS host and server security protection: SSH modification port, add Whitelist, key login only.

PS: Updated on March 19, 2020 , if your website has been hacked, you can refer to the following methods to solve the problem: Website Trojans and server hacking troubleshooting analysis - VPS host and server security methods.

1. PHP code blocks specific IP

The PHP code is relatively simple. Just throw the following code into your PHP file to prevent IPs within a specific range from accessing the website. According to the accuracy of the IP library, it can be accurate to the IPs at the national, provincial, municipal and other levels. The code An example is as follows (this code can be used during BA):

<?php
/**
 *
 * test.php(屏蔽国家IP)
 *
 */

$verification = '美国';//需要屏蔽国家的IP
function get_client_ip() { 
               $ip = $_SERVER['REMOTE_ADDR'];     
         if (isset($_SERVER['HTTP_X_REAL_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_FORWARDED_FOR'])) {            
         $ip = $_SERVER['HTTP_X_REAL_FORWARDED_FOR'];       
         }          
         elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {             
         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];       
         }          
         elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {           
         $ip = $_SERVER['HTTP_CLIENT_IP'];       
         }          
         return $ip;    
         }
$ip = get_client_ip();//获取访客IP
$antecedents = $_SERVER['HTTP_REFERER'];//访客来路地址
$result = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);//IP数据库来自淘宝。
$address = json_decode($result,true);
//判断访客是否属于美国,是否来自百度,是否来自谷歌
if($address['data']['country'] == $verification && strpos($antecedents, 'baidu') === false && strpos($antecedents, 'google') === false){
        sleep(10);//设置一个10秒等待。
        header('HTTP/1.1 503 Service Temporarily Unavailable');
        header('Status: 503 Service Temporarily Unavailable');
        header('Retry-After: 3600000');
        exit;
}


/****** 如果需要阻止某一个省份的IP访问,使用以下代码*********/


<?php
/**
 *
 * test.php(屏蔽地方IP)
 *
 */

$verification = '江西省';//需要屏蔽省份的IP
function get_client_ip() { 
               $ip = $_SERVER['REMOTE_ADDR'];     
         if (isset($_SERVER['HTTP_X_REAL_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_FORWARDED_FOR'])) {            
         $ip = $_SERVER['HTTP_X_REAL_FORWARDED_FOR'];       
         }          
         elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {             
         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];       
         }          
         elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {           
         $ip = $_SERVER['HTTP_CLIENT_IP'];       
         }          
         return $ip;    
         }
$ip = get_client_ip();//获取访客IP
$antecedents = $_SERVER['HTTP_REFERER'];//访客来路地址
$result = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);//IP数据库来自淘宝。
$address = json_decode($result,true);
//判断访客是否属于江西省,是否来自百度,是否来自谷歌
if($address['data']['region'] == $verification && strpos($antecedents, 'baidu') === false && strpos($antecedents, 'google') === false){
  sleep(99999999);//设置一个999999秒的等待。
  Header("HTTP/1.1 204 No Content");
  exit;
}

2. Nginx-ngx_http_geoip_module module

IP library download:

  1. HTTPS://Dev.马Xiumin's.com/Geo IP/legacy/geohlit/

2.1  Ban access from specific country IPs

The ngx_http_geoip_module module allows Nginx to implement different needs based on the visitor's IP. Here we use the ngx_http_geoip_module module to prevent specific IP addresses from accessing the website.

The first is to compile ngx_http_geoip_module into Nginx. If you are using the Pagoda BT panel, you can use the following command:

#安装geoip库
yum -y install epel-release
yum -y install geoip-devel


#先查看一下本机的Nginx配置情况
[root@cs ~]# nginx -V
nginx version: nginx/1.14.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
built with OpenSSL 1.0.2l  25 May 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/www/server/nginx --with-openssl=/www/server/nginx/src/openssl --add-module=/www/server/nginx/src/ngx_devel_kit --add-module=/www/server/nginx/src/lua_nginx_module --add-module=/www/server/nginx/src/ngx_cache_purge --add-module=/www/server/nginx/src/nginx-sticky-module --add-module=/www/server/nginx/src/nginx-http-concat --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_image_filter_module --with-http_gzip_static_module --with-http_gunzip_module --with-stream --with-stream_ssl_module --with-ipv6 --with-http_sub_module --with-http_flv_module --with-http_addition_module --with-http_realip_module --with-http_mp4_module --with-ld-opt=-Wl,-E --with-pcre=pcre-8.40 --with-ld-opt=-ljemalloc

#开始下载Nginx,这里用的是1.15.1,你也可以下载其它的版本
wget http://nginx.org/download/nginx-1.15.1.tar.gz
tar -xzvf nginx-1.15.1.tar.gz
cd nginx-1.15.1

#下面的命令只是在上面的Nginx -v得到的配置详情后加上了--with-http_geoip_module,目的是为了保持原来的配置不变同时又增加新的模块

./configure --user=www --group=www --prefix=/www/server/nginx --with-openssl=/www/server/nginx/src/openssl --add-module=/www/server/nginx/src/ngx_devel_kit --add-module=/www/server/nginx/src/lua_nginx_module --add-module=/www/server/nginx/src/ngx_cache_purge --add-module=/www/server/nginx/src/nginx-sticky-module --add-module=/www/server/nginx/src/nginx-http-concat --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_image_filter_module --with-http_gzip_static_module --with-http_gunzip_module --with-stream --with-stream_ssl_module --with-ipv6 --with-http_sub_module --with-http_flv_module --with-http_addition_module --with-http_realip_module --with-http_mp4_module --with-ld-opt=-Wl,-E --with-pcre=pcre-8.40 --with-ld-opt=-ljemalloc --with-http_geoip_module

#只编译不安装
make

If you are using LNMP script or Oneinstack, you can refer to here: Oneinstack. Enable Nginx-ngx_http_geoip_module module. Disable Nginx first.

Then replace the new Nginx and see if the geoip module has been loaded. The command is as follows:

mv /www/server/nginx/sbin/nginx /www/server/nginx/sbin/nginx-lala.im
cp objs/nginx /www/server/nginx/sbin/nginx
ldd /www/server/nginx/sbin/nginx

Go to your Pagoda panel, click Nginx, modify the configuration file, and add the following code:

geoip_country /usr/share/GeoIP/GeoIP.dat;

The operation is as follows:

Now start Nginx, you can add rules to the Nginx configuration of the website. For example, you can return a specified error or direct IP access to another page or website from a specific country. Code example:

#返回403 502 404等错误
location / {
default_type text/html;
charset utf-8;
if ($geoip_country_code = CN) {
return 403;
}
}
#导向另一个网站目录
location / {
default_type text/html;
charset utf-8;
if ($geoip_country_code = CN) {
root /home/www/wzfou.com-cn/;
}
}

This is to add website configuration.

The final effect is as follows:

2.2  Only allow IP access from specified countries

The method is the same as above. First introduce the IP library in the Nginx main configuration, and then add code that blocks any national IP but allows specified national IPs in the Nginx configuration of the website. The example is as follows:

 # 引入IP库
     
  geoip_country /usr/share/GeoIP/GeoIP.dat;
  geoip_city /usr/share/GeoIP/GeoLiteCity.dat;


 map $geoip_country_code $allowed_country {
                default no;
                CN yes;
        }
    
# 在配置中阻止IP
        if ($allowed_country = no) {
                return 403;
        }

3. iptables firewall

First, familiarize yourself with iptables usage and ipset:

1. iptables contains several tables, each table is composed of chains. The default is the filter table, the most commonly used is the filter table, and the other more commonly used is the nat table. Generally, IP blocking is to add rules to the INPUT chain of the filter table.

2. When matching rules, match them one by one from the beginning to the end of the rule list.

3. ipset provides a method to turn this O(n) operation into O(1): put the IP to be processed into a set and set an iptables rule for this set. Like iptable, IP sets are something in the Linux kernel, and the ipset command is a tool to operate them.

iptables only allows specified IP to access the specified port of the machine. The command is as follows:

1、在tcp协议中,禁止所有的ip访问本机的3306端口。

iptables -I INPUT -p tcp –dport 3306 -j DROP

2、允许123.456.789访问本机的3306端口

iptables -I INPUT -s 123.456.789 -p tcp –dport 3306 -j ACCEPT

以此类推…………………………………

封掉一个IP段:
iptables -I INPUT -s 121.0.0.0/8 -j DROP

以上命令的顺序不能错

然后保存iptables
# service iptables save
重启防火墙
#service iptables restart

How to delete, clear, close and save iptables rules:

#CentOS 7请停止firewalld并安装iptables-services
systemctl stop firewalld
systemctl mask firewalld

#安装 iptables-services
yum install iptables-services

################
保存 iptables 规则
service iptables save

重启 iptables
service iptables restart

#################
执行清除命令 iptables -F时可能会断开与服务器的连接,如果想清空的话,先执行
/sbin/iptables -P INPUT ACCEPT
然后执行
/sbin/iptables -F

如果关闭防火墙,执行 
/etc/init.d/iptables stop   
或者是 services iptables stop  

#######################
iptables 规则若重启后消失,请用以下方法
步骤1:备份
iptables-save > /etc/iptables.up.rules.bak

步骤2:删除规则
vim /etc/sysconfig/iptables
或 vim /etc/iptables.up.rules

手动删除即可。

步骤3:导入新规则

iptables-restore < /etc/sysconfig/iptables

最后,重启VPS就可以生效了。

3.1  Block IP access from specified countries with one click

  1. HTTPS://GitHub.com/III i III1/block-IPS-from-countries

The principle is to download the IP segment of the specified country, then add the IP segment to the iptables rules, and directly execute the following command:

wget https://raw.githubusercontent.com/iiiiiii1/Block-IPs-from-countries/master/block-ips.sh
chmod +x block-ips.sh
./block-ips.sh

You will then be asked to choose whether to block the IP or unblock the IP.

After choosing to block the IP, you will be asked to enter the country code. Please check here: http://www.ipdeny.com/ipblocks. For example, for the United States, enter us. Make sure to complete the IP ban for the entire US.

If you want to unblock it, execute the command again and select 2.

3.2  Allow only specified country IP access with one click

Above we have implemented one-click blocking of IP access from a specific country, but many people want to allow their website to only be accessed by IPs from a certain country, and prohibit access to others. In this case, we can use the following command:

wget https://do.wzfou.net/wzfou/block-any.sh
chmod +x block-ips.sh
./block-ips.sh

The above code only allows domestic IP access, and will write the rules in: /etc/rc.d/rc.local. The iptables rules will be re-imported every time the system is restarted. If you adjust the iptables rules, you need to edit: / etc/rc.d/rc.local delete the corresponding startup self-running code. block-any.sh code is as follows:

#! /bin/bash
#判断是否具有root权限
root_need() {
    if [[ $EUID -ne 0 ]]; then
        echo "Error:This script must be run as root!" 1>&2
        exit 1
    fi
}

#检查系统分支及版本(主要是:分支->>版本>>决定命令格式)
check_release() {
    if uname -a | grep el7  ; then
        release="centos7"
    elif uname -a | grep el6 ; then
        release="centos6"
        yum install ipset -y
    elif cat /etc/issue |grep -i ubuntu ; then
        release="ubuntu"
        apt install ipset -y
    fi
}

#安装必要的软件(wget),并下载中国IP网段文件(最后将局域网地址也放进去)
get_china_ip() {
  #安装必要的软件(wget)
  rpm --help >/dev/null 2>&1 && rpm -qa |grep wget >/dev/null 2>&1 ||yum install -y wget ipset >/dev/null 2>&1 
  dpkg --help >/dev/null 2>&1 && dpkg -l |grep wget >/dev/null 2>&1 ||apt-get install wget ipset -y >/dev/null 2>&1

  #该文件由IPIP维护更新,大约一月一次更新(也可以用我放在国内的存储的版本,2018-9-8日版)
  [ -f china_ip_list.txt ] && mv china_ip_list.txt china_ip_list.txt.old
  wget https://github.com/17mon/china_ip_list/blob/master/china_ip_list.txt
  cat china_ip_list.txt |grep 'js-file-line">' |awk -F'js-file-line">' '{print $2}' |awk -F'<' '{print $1}' >> china_ip.txt
  rm -rf china_ip_list.txt
  #wget https://qiniu.wsfnk.com/china_ip.txt

  #放行局域网地址
  echo "192.168.0.0/18" >> china_ip.txt
  echo "10.0.0.0/8" >> china_ip.txt
  echo "172.16.0.0/12" >> china_ip.txt
}

#只允许国内IP访问
ipset_only_china() {
  echo "ipset create whitelist-china hash:net hashsize 10000 maxelem 1000000" > /etc/ip-black.sh
  for i in $( cat china_ip.txt )
  do
        	echo "ipset add whitelist-china $i" >> /etc/ip-black.sh
  done
  echo "iptables -I INPUT -m set --match-set whitelist-china src -j ACCEPT" >> /etc/ip-black.sh
  #拒绝非国内和内网地址发起的tcp连接请求(tcp syn 包)(注意,只是屏蔽了入向的tcp syn包,该主机主动访问国外资源不用影响)
  echo "iptables  -A INPUT -p tcp --syn -m connlimit --connlimit-above 0 -j DROP" >> /etc/ip-black.sh
  #拒绝非国内和内网发起的ping探测(不影响本机ping外部主机)
  echo "iptables  -A INPUT -p icmp -m icmp --icmp-type 8 -j DROP" >> /etc/ip-black.sh
  #echo "iptables -A INPUT -j DROP" >> /etc/ip-black.sh
  rm -rf china_ip.txt
}

run_setup() {
  chmod +x /etc/rc.local
  sh /etc/ip-black.sh
  rm -rf /etc/ip-black.sh
  #下面这句主要是兼容centos6不能使用"-f"参数
  ipset save whitelist-china -f /etc/ipset.conf || ipset save whitelist-china > /etc/ipset.conf
  [ $release = centos7 ] && echo "ipset restore -f /etc/ipset.conf" >> /etc/rc.local
  [ $release = centos6 ] && echo "ipset restore < /etc/ipset.conf" >> /etc/rc.local
  echo "iptables -I INPUT -m set --match-set whitelist-china src -j ACCEPT" >> /etc/rc.local
  echo "iptables  -A INPUT -p tcp --syn -m connlimit --connlimit-above 0 -j DROP" >> /etc/rc.local
  echo "iptables  -A INPUT -p icmp -m icmp --icmp-type 8 -j DROP" >> /etc/rc.local
  #echo "iptables -A INPUT -j DROP" >> /etc/rc.local
}

main() {
  check_release
  get_china_ip
  ipset_only_china

case "$release" in
centos6)
  run_setup
  ;;
centos7)
  chmod +x /etc/rc.d/rc.local
  run_setup
  ;;
ubuntu)
  sed -i '/exit 0/d' /etc/rc.local
  run_setup
  echo "exit 0" >> /etc/rc.local
  ;;
esac
}
main

If you want to exclude some IPs and allow these IPs to continue accessing as exceptions, you can use the iptables -I command to add iptables rules, or add iptables rules manually. Be careful to put the rules at the top, because the order of iptables execution is from top to bottom. .

3.3  Manually set to only allow IP access from specific countries

Manual setting is the same as the one-click setting method above. Just follow the following commands one by one.

1、安装ipset

#Debian/Ubuntu系统
apt-get -y install ipset

#CentOS系统
yum -y install ipset
CentOS 7还需要关闭firewall防火墙:

systemctl stop firewalld.service
systemctl disable firewalld.service

2、清空之前的规则

#防止设置不生效,建议清空下之前的防火墙规则
iptables -P INPUT ACCEPT
iptables -F

3、创建新规则

#创建一个名为cnip的规则
ipset -N cnip hash:net
#下载国家IP段,这里以中国为例,其它国家IP下载参考:http://www.ipdeny.com/ipblocks/
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
#将IP段添加到cnip规则中
for i in $(cat /root/cn.zone ); do ipset -A cnip $i; done

4、设置IP段白名单

#放行IP段
iptables -A INPUT -p tcp -m set --match-set cnip src -j ACCEPT
#关掉所有端口
iptables -P INPUT DROP
这时候就只有指定国家的IP能访问服务器了。

#如果你在国内,网站不允许被国内人访问,建议别关所有端口,这样你的S-S-H会上不去,我们可以只关闭80/443端口。

#关闭指定端口,比如80/443
iptables -A INPUT -p tcp --dport 80 -j DROP
iptables -A INPUT -p tcp --dport 443 -j DROP
这时候其他国家的IP是无法访问你服务器的80/443端口,等于无法访问你的网站,其它端口还是可以访问的。

5、删除规则

#将参数里的-A改成-D就是删除规则了,如
iptables -D INPUT -p tcp -m set --match-set cnip src -j ACCEPT
iptables -D INPUT -p tcp --dport 443 -j DROP

4. WordPress blocks specific IPs

WordPress plugin

  1. HTTPS://WordPress.org/plugins/word volume/
  2. HTTPS://WordPress.org/plugins/all-in-one-I'm afraid-security-安定-firewall/
  3. HTTPS://WordPress.org/plugins/IP-geoh-block/

The above three WordPress security plug-ins all have settings to block IP access, which can be blocked based on the source, country, range and domain name of the IP. (Click to enlarge)

IP Geo Block is slightly more professional. In addition to blocking specific IP addresses, it can also block or prevent different IP addresses from accessing different pages. It is very powerful. (Click to enlarge)

5. Summary

The simplest way for a website to block the IP of a specific country is the PHP code introduced in this article, which refers to the Taobao IP library. The accuracy is very high, and it can also be accurate to the province and city. You can adjust it according to your needs. The disadvantage is that it does not support HTTPS and can only run in PHP.

In fact, the most commonly used one is iptables, which directly blocks IP access in the way of Linux firewall. It does not consume resources and blocks it cleanly and completely. Nginx's Geo IP module has a wide range of applications. Combined with Nginx, you can display different content to different IP users.

Leave a Reply