nginx使用GeoIP限制访问并支持白名单

要使用GeoIP,需要重新编译Nginx,我的系统是centos6.5,nginx用的是tengine,需要的软件包:
gcc、gcc-c++、 openssl、 openssl-devel、geoIP library、GeoLite Country、GeoLite City、pcre、tengine2

1.下载需要的软件包

wget http://tengine.taobao.org/download/tengine-2.0.3.tar.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.33.zip

2.安装编译用到的软件

yum install gcc gcc-c++ openssl openssl-devel

3.编译GeoIP library

gunzip GeoIP.tar.gz && tar -xvf GeoIP.tar && cd GeoIP-1.4.8 
./configure && make && make install

如果不编译GeoIP library,在编译nginx时会提示

the GeoIP module requires the GeoIP library

4.编译nginx
先解压pcre在执行已下命令:

./configure --prefix=/usr/local/nginx --with-http_realip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_stub_status_module --without-select_module --without-poll_module --with-http_geoip_module --with-http_ssl_module --with-openssl-opt=enable-tlsext --with-pcre=../pcre-8.33
make && make install

5.配置GeoIP

gunzip GeoLiteCity.dat.gz  && gunzip GeoIP.dat.gz

将这两个解压后的库文件移到nginx的conf目录下,之后在nginx.conf中加入:

geoip_country /usr/local/nginx/conf/GeoIP.dat;
geoip_city /usr/local/nginx/conf/GeoLiteCity.dat;
#geoIP的白名单
geo $remote_addr $ip_whitelist {
default 0;
include ip.conf;
}

在要使用geoIP的虚拟主机中的location中加入GeoIP配置,这里直接贴一个配置

location / {
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#白名单配置
if ($ip_whitelist = 1) {
proxy_pass http://web;
break;
}
#屏蔽的国家返回403
if ($geoip_country_code ~ "(HK|TW|PH|MO|US)") {
return 403;
}
proxy_pass http://web;
}

在conf下新建一个ip.conf作为Geoip的白名单,支持ip段,内容和格式为:

8.8.8.8 1;
8.8.8.8/24 1;

检查配置

/usr/local/nginx/sbin/nginx -t

如果是64位系统可能会报:

/nginx: error while loading shared libraries: libGeoIP.so.1: cannot open shared object file: No such file or directory

解决方法:

ln -s /usr/local/lib/libGeoIP.so* /lib64/

之后

ldd /usr/local/nginx/sbin/nginx 

确认下没有not found的库文件即可。
这样就配置好了nginx,并且通过GeoIP限制了国家和城市的访问,并且支持白名单。

原文链接:http://www.52os.net/articles/configure-nginx-using-geoip-allow-whitelist.html

原文地址:https://www.cnblogs.com/lsan/p/4629489.html