Docs/linux基础/nginx/Geoip2/Geoip限制访问.md
2022-10-18 16:59:37 +08:00

3 KiB
Raw Blame History

注意本文档nginx版本为1.18.0根据系统中安装的nginx版本下载对应安装包

1、查看nginx版本

# 切换到nginx二进制执行文件所在目录
# 假设nginx安装在/usr/local/nginx目录中
cd /usr/local/nginx/
./sbin/nginx -v

显示结果类似

nginx version: nginx/1.18.0

2、下载对应版本的nginx

wget http://nginx.org/download/nginx-1.18.0.tar.gz -O ~/nginx-1.18.0.tar.gz

3、下载geoip2识别库、第三方模块及geoip2地址库

# geoip2地址识别库
wget https://github.com/maxmind/libmaxminddb/releases/download/1.6.0/libmaxminddb-1.6.0.tar.gz -O ~/libmaxminddb-1.6.0.tar.gz

# 第三方模块
wget https://github.com/leev/ngx_http_geoip2_module/archive/refs/tags/3.3.tar.gz -O ngx_http_geoip2_module.tar.gz

# geoip2地址库需要注册登录下载
# 下载地址为https://www.maxmind.com/en/accounts/current/geoip/downloads
# 已下载,见文件[GeoLite2-Country_20210615.tar.gz]

4、安装识别库

cd ~
tar zxvf libmaxminddb-1.6.0.tar.gz
cd libmaxminddb-1.6.0
./configure && make && make install
echo /usr/local/lib  >> /etc/ld.so.conf.d/local.conf
ldconfig

5、查看nginx编译参数

./sbin/nginx -V

复制编译参数

6、编译安装nginx

tar zxvf ngx_http_geoip2_module.tar.gz -C /etc/nginx/modules
tar zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0
./configure 【步骤5中的编译参数】 --add-dynamic-module=/etc/nginx/modules/ngx_http_geoip2_module-3.3
make && make install
# 检查/etc/nginx/modules/目录中是否存在ngx_http_geoip2_module.so与ngx_stream_geoip2_module.so
# 若不存在复制nginx-1.18.0/objs目录下对应的so文件到/etc/nginx/modules/中

7、配置nginx

nginx.conf添加以下两行配置与http配置块同级
...
load_module /etc/nginx/modules/ngx_http_geoip2_module.so;
load_module /etc/nginx/modules/ngx_stream_geoip2_module.so;
...
geoip2地址库配置
mkdir /etc/nginx/GeoIP
tar zxvf GeoLite2-Country_20210615.tar.gz -C /etc/nginx/GeoIP
tar zxvf GeoLite2-City_20210615.tar.gz -C /etc/nginx/GeoIP
ln -s /etc/nginx/GeoIP/GeoLite2-City_20210615 /etc/nginx/GeoIP/City
nginx.conf的http配置块中添加以下配置
http {
    ...
    # 国家或地区
    geoip2 /etc/nginx/GeoIP/Country/GeoLite2-Country.mmdb {
        $geoip2_country_code source=$remote_addr country iso_code;
    }
    
    # 城市
    geoip2 /etc/nginx/GeoIP/City/GeoLite2-City.mmdb {
        $geoip2_city_name_en default=ShangHai city names en;
    }

    map $geoip2_country_code $allowed_country {
        default yes;
        CN no;
    }
    
    map $geoip2_city_name_en $allowed_city {
        default yes;
        Haikou no;
        Meilan no;
    }
    ...
}
nginx.conf的server配置块中添加以下配置
server {
    ...
    # 限制allowed_country为no的国家或地区访问
    if ($allowed_country = no) { return 503;}

    # 限制allowed_city为no的城市访问
    if ($allowed_city = no) {return 600;}
    ...
    location ...
}
重启nginx