GeoIP库与ngx_http_geoip_module模块

  sre


ngx_http_geoip_module模块(0.8.6+)创建变量,使用预编译的MaxMind数据库解析客户端IP地址,得到变量值。
nginx默认不编译这个模块,需要开启–with-http_geoip_module编译选项。

#安装 MaxMind 的 GeoIP 库
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
tar -zxvf GeoIP.tar.gz
cd GeoIP-1.4.8
./configure
make -j 8 && make install
加到动态链接配置里:
echo ‘/usr/local/lib’ > /etc/ld.so.conf.d/geoip.conf
ldconfig

#重新编译nginx,需要先编译GeoIP库
./configure –user=www –group=www –prefix=/usr/local/nginx –with-http_stub_status_module –with-http_ssl_module –with-http_v2_module –with-http_gzip_static_module –with-ipv6 –with-http_sub_module –with-openssl=../openssl-1.0.2n –with-openssl-opt=enable-tls1_3 –with-ld-opt=-ljemalloc –with-http_geoip_module –add-module=../nginx-rtmp-module-master –add-module=../ngx_devel_kit-0.3.0 –add-module=../lua-nginx-module-0.10.12rc1 –add-module=../echo-nginx-module –with-stream –with-stream_ssl_module –add-module=../nginx_cookie_flag_module-master –add-module=../headers-more-nginx-module –add-module=../ngx_http_substitutions_filter_module
make -j 8 && make install
#./configure: error: the GeoIP module requires the GeoIP library.
#You can either do not enable the module or install the library.

# 下载IP地域数据库 http://dev.maxmind.com/geoip/legacy/geolite/
mkdir -p /data/nginx/conf/GeoIP
cd /data/nginx/conf/GeoIP
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz

#在 http区增加数据库调用
geoip_country /data/nginx/conf/GeoIP/GeoIP.dat;
geoip_city /data/nginx/conf/GeoIP/GeoLiteCity.dat;

#常用变量
location / {
default_type ‘text/plain’;
echo remote_addr; #IP
echo
geoip_country_code; #双字符国家代码,比如 “RU”,“US”
echo geoip_country_name; #国家名称,比如 “Russian Federation”,“United States”。
echo
geoip_region; #国家行政区名(行政区、直辖区、州、省、联邦管辖区,诸如此类),比如 “Shanxi”

echo geoip_postal_code; #城市的邮政编码。经测试,国内这字段为空

echogeoip_city; #城市名称,比如 “Xian”
echo geoip_city_country_code; #也是两位字符的英文国家码。
echo
geoip_city_country_code3; #三字符国家代码,比如 “RUS”,“USA”。
echo geoip_city_country_name; #上同.
echo
geoip_city_continent_code; #所在洲,如AS

echo geoip_latitude; #纬度
echo
geoip_longitude; #经度

}

#调用,如:
if (geoip_country_code = CN) {
deny all;
}

if (geoip_region != 12) {
return 403 “region error”;
}

#$geoip_region相应的省份代码:
CN,01,”Anhui”
CN,02,”Zhejiang”
CN,03,”Jiangxi”
CN,04,”Jiangsu”
CN,05,”Jilin”
CN,06,”Qinghai”
CN,07,”Fujian”
CN,08,”Heilongjiang”
CN,09,”Henan”
CN,10,”Hebei”
CN,11,”Hunan”
CN,12,”Hubei”
CN,13,”Xinjiang”
CN,14,”Xizang”
CN,15,”Gansu”
CN,16,”Guangxi”
CN,18,”Guizhou”
CN,19,”Liaoning”
CN,20,”Nei Mongol”
CN,21,”Ningxia”
CN,22,”Beijing”
CN,23,”Shanghai”
CN,24,”Shanxi”
CN,25,”Shandong”
CN,26,”Shaanxi”
CN,28,”Tianjin”
CN,29,”Yunnan”
CN,30,”Guangdong”
CN,31,”Hainan”
CN,32,”Sichuan”
CN,33,”Chongqing”

LEAVE A COMMENT

Captcha Code