目录
1、安装依赖环境
yum install geoip geoip-devel -y
2、下载安装IP数据库
官网下载页面 https://www.maxmind.com/en/accounts/758766/geoip/downloads
或者使用网上资源下载
wget https://pan.k8scn.work:15443/d/ChinaNetCould/datafiles/geoip-20221011/GeoLite2-ASN_20221011.tar.gz
wget https://pan.k8scn.work:15443/d/ChinaNetCould/datafiles/geoip-20221011/GeoLite2-City_20221011.tar.gz
wget https://pan.k8scn.work:15443/d/ChinaNetCould/datafiles/geoip-20221011/GeoLite2-Country_20221011.tar.gz
解压到指定目录
tar xvf GeoLite2-ASN*.tar.gz -C /usr/local/geoip/
tar xvf GeoLite2-City*.tar.gz -C /usr/local/geoip/
tar xvf GeoLite2-Country*.tar.gz -C /usr/local/geoip/
重命名
mv /usr/local/geoip/GeoLite2-City*/ /usr/local/geoip/GeoLite2-City/
mv /usr/local/geoip/GeoLite2-Country*/ /usr/local/geoip/GeoLite2-Country/
mv /usr/local/geoip/GeoLite2-ASN*/ /usr/local/geoip/GeoLite2-ASN/
3、安装mmdblookup环境,
yum install -y libmaxminddb-devel
查看ip所属位置
mmdblookup --file /usr/local/geoip/GeoLite2-City/GeoLite2-City.mmdb --ip 183.195.99.161
4、下载geoip2模块的代码
4.1 安装编译环境
yum install -y libunwind-devel.x86_64 systemd-devel libatomic_ops-devel lua-devel
4.2 下载geoip2模块的代码
(注:模块保存路径/usr/local/src)
wget https://github.com/leev/ngx_http_geoip2_module/archive/master.zip
4.3 安装google-pertools
wget -c -O gperftools-2.10.tar.gz https://github.com/gperftools/gperftools/releases/download/gperftools-2.10/gperftools-2.10.tar.gz
tar xvf gperftools-2.10.tar.gz
mv gperftools-2.10 /usr/local/src/
cd /usr/local/src/gperftools-2.10
./configure
make check && make install
5、nginx配置geoip2
每次修改之后要重新启动nginx nginx -s reload
5.1 重新配置nginx
进入nginx解压目录,配置geoip2模块。若之前配置好,可以忽略
./configure --with-http_geoip_module=dynamic --add-module=/usr/local/src/ngx_http_geoip2_module
make
make install
5.2 修改nginx.conf
http {
include mime.types;
default_type application/octet-stream;
log_format main escape=json '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time '
'"$geoip2_data_country_name" "$geoip2_data_city_name" ';
access_log /usr/local/nginx/logs/geoip-access.log;
geoip2 /usr/local/geoip/GeoLite2-Country/GeoLite2-Country.mmdb{
$geoip2_data_country_code country iso_code ;
$geoip2_data_country_name country names zh-CN;
}
geoip2 /usr/local/geoip/GeoLite2-City/GeoLite2-City.mmdb {
$geoip2_data_country_code country iso_code;
$geoip2_data_country_name country names zh-CN;
$geoip2_data_city_name city names zh-CN;
$geoip2_data_province_name subdivisions 0 names en;
$geoip2_data_province_isocode subdivisions 0 iso_code;
$geoip2_continent_code continent code;
$geoip2_data_city_name default=China;
}
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
if ($geoip2_data_city_name !~ "Shanghai") {
return 404;
}
listen 80;
server_name localhost;