标签归档:ip限制

nginx通过GeoIP模块限制国家地区用户访问(Debian/Ubuntu/CentOs环境)

本文介绍如何使用GeoIP模块让nginx实现限制某个地区用户访问的功能。nginx要加上 –with-http_geoip_module 参数进行编译。

1、首先我们检查一下nginx是否编译了GeoIP模块

nginx -V

如果你在输出界面看到了 –with-http_geoip_module,那么就说明nginx已经编译了GeoIP模块。

2、接下来我们安装GeoIP数据库
在Debian/Ubuntu系统,我们可以执行下面的命令进行安装:

apt-get install geoip-database libgeoip1

CentOS安装办法:  yum -y install geoip-devel

安装完成之后,GeoIP数据库会被安装在 /usr/share/GeoIP/GeoIP.dat。

这个GeoIP.dat是GeoIP数据库文件,使用apt-get命令安装的话这个文件不是最新的,我们可以从 http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz 这里下载最新的GeoIP数据库文件。

mv /usr/share/GeoIP/GeoIP.dat /usr/share/GeoIP/GeoIP.dat_bak

cd /usr/share/GeoIP/
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz

3、现在来配置nginx.conf文件

vi /etc/nginx/nginx.conf

将下面的内容添加进 http {} 区域,并且要放在任何 include 语句之前。

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default yes;
FK no;
FM no;
EH no;
}

上面这些语句是除了 FK,FM,EH这三个地区的用户允许其它地区的用户访问。

也可以只允许部分地区用户访问:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
FK yes;
FM yes;
EH yes;
}

上面这些语句是除了 FK,FM,EH这三个地区的用户其它地区的用户都不允许访问。

上面的语句只是设置了一个 $allowed_country 变量,要最终实现禁止设置的地区用户访问,我们要对 $allowed_country 变量进行判断处理。
在 server {} 区域里添加以下内容:

if ($allowed_country = no) {
return 403;
}

也可以针对某个特定url进行限制:

location /special {
if ($allowd_country = no) {
return 403;
}
}

配置 中国用户访问其他目录 nginx,在相关地方加上如下的配置就可以了:

# vi /etc/nginx/nginx.conf

http {
...
geoip_country /home/vpsee/GeoIP.dat;
fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
...
}

server {
...
        location / {
            root   /home/vpsee/www;
            if ($geoip_country_code = CN) {
                root /home/vpsee/cn;
            }
            ...
        }
...
}

这样,当来自中国的 IP 访问网站后就自动访问到预定的 /home/vpsee/cn 页面。关于 Nginx + GeoIP 还有很多有用的用法,比如做个简单的 CDN,来自中国的访问自动解析到国内服务器、来自美国的访问自动转向到美国服务器等。MaxMind 还提供了全球各个城市的 IP 信息,还可以下载城市 IP 数据库来针对不同城市做处理。

4、重启nginx

/etc/init.d/nginx reload

这样我们就实现了nginx限制某个地区用户访问的功能。