一、安裝 geoip2 擴(kuò)展依賴 libmaxminddb
# 編譯安裝
cd /usr/local/src
wget https://github.com/maxmind/libmaxminddb/releases/download/1.6.0/libmaxminddb-1.6.0.tar.gz
tar xf libmaxminddb-1.6.0.tar.gz
cd libmaxminddb-1.6.0/
./configure && make && make install
echo "/usr/local/lib" >> /etc/ld.so.conf
ldconfig
或者使用yum安裝
yum install libmaxminddb-devel -y
二、下載 ngx_http_geoip2_module 模塊
cd /usr/local/src
wget https://github.com/leev/ngx_http_geoip2_module/archive/refs/tags/3.4.tar.gz
tar xf 3.4.tar.gz
mv ngx_http_geoip2_module-3.4 ngx_http_geoip2_module
三、安裝 nginx 模塊
1、安裝依賴
yum -y install pcre-devel openssl-devel perl-devel libxml2
2、下載編譯安裝
cd /usr/local/src
wget http://nginx.org/download/nginx-1.22.0.tar.gz
tar xf nginx-1.22.0.tar.gz
cd nginx-1.22.0
groupadd nginx
useradd -g nginx nginx
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-file-aio --with-pcre --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_v2_module --with-http_ssl_module --with-stream --add-module=/usr/local/src/ngx_http_geoip2_module
make
make install
擴(kuò)展:
如果用 動態(tài)模塊
./configure ... --add-dynamic-module=/usr/local/src/ngx_http_geoip2_module
后面在 nginx.conf 文件的http中,需要添加一行
load_module /usr/lib64/nginx/modules/ngx_http_geoip2_module.so ;
備注:如果是重新編譯nginx,只需要到 make 這一步,不需要執(zhí)行 make install,make 好以后,把 objs/nginx 拷貝到 /usr/local/nginx/sbin/nginx ,重新啟動即可。
四、下載最新的 IP 地址數(shù)據(jù)庫文件GeoLite2-Country.mmdb
cd /usr/local/nginx/conf/
mkdir geoip2
cd geoip2
wget https://github.com/P3TERX/GeoLite.mmdb/releases/download/2022.08.31/GeoLite2-Country.mmdb
五、添加geoip訪問策略
1、在 http 中添加 幾行,定義數(shù)據(jù)庫文件位置
http {
....
geoip2 /usr/local/nginx/conf/geoip2/GeoLite2-Country.mmdb {
auto_reload 5m ;
$geoip2_country_code country iso_code;
}
map $geoip2_country_code $allowed_country {
default yes;
CN no;
}
....
}
2、在server中添加
#前端Nginx配置頁面必須添加.
server {
listen 80;
server_name xxx.xxx.com
....
# 匹配國家代碼定義為no的,禁止訪問,返回403(上面定義中國的 iso_code 為no)
if ( $allowed_country = no ) { return 403; }
# 403錯誤跳轉(zhuǎn)至指定二級頁面
error_page 404 403 500 = https://error.xxx.com/;
....
}
3、啟動Nginx
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf