nginx配置 geoip2限制 不同地区访问网站

一、安装libmaxminddb

yum install libmaxminddb-devel -y

下载 https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz 并编译

tar -xzf libmaxminddb-1.3.2.tar.gz
cd libmaxminddb-1.3.2
./configure
make
make check 
sudo make install
sudo ldconfig

二、下载geoip2数据库文件

geoip2下载离线数据库库需要注册用户才可下载。官方网址https://www.maxmind.com/en/home
在这里插入图片描述
下载到本地后,然后上传至服务器,放到服务器目录下

三、nginx安装geoip2模块

nginx必须1.15往上

3.1首先下载nginx的第三方模块ngx_http_geoip2_module ,下载地址https://github.com/leev/ngx_http_geoip2_module/
3.2
然后对nginx增加ngx_http_geoip2_module模块

#下载后解压至/home/user/
#你的nginx安装目录下执行,如果你之前有手动安装过其他模块,也要在后面加上
sudo ./configure --prefix=你的nginx安装路径 --add-module=/opt/ngx_http_geoip2_module-master/
sudo make install
#只执行make即可。正常情况下会在安装目录下的objs目录下生成新的nginx二进制文件,替换运行中nginx的即可,可把当前nginx备份一下。
#替换后执行
./nginx -V
# 即可看见添加的 ngx_http_geoip2_module 

3.3测试是否安装成功

mmdblookup --file /opt/fy/3rd/GeoIP/GeoLite2-City_20210406/GeoLite2-City.mmdb --ip  220.181.38.148 
# --file 后面跟的是上面解压后的mmdb文件地址
# --ip 则是你要查询的ip

在这里插入图片描述
如果上面命令返回这些 那么就证明配置成功了 接下来在nginx配置

四、nginx配置geoip2

所有国家代码的列表 https://dev.maxmind.com/geoip/legacy/codes/iso3166/


#http 下新增
geoip2 /home/user/GeoLite2-Country_20210406/GeoLite2-Country.mmdb{
            #$geoip2_data_city_name source=$remote_addr country names en; 
            $geoip2_data_country_code source=$remote_addr country iso_code;
}
#注意,这里的source是重点,把访问的真实ip当做来源配置。    
#或者用map
#配置1: 允许所有国家访问,除了美国和日本
map $geoip2_data_country_code $allowed_country {
    default yes;
    US no;
    JP no;
}

#配置2: 只允许中国访问,可以在后面叠加可访问的国家iso_code;
map $geoip2_data_country_code $allowed_country {
    default no;
    CN yes;
   
}

server 下增加

#简单用法
location / {
  if ($geoip2_data_country_code != CN ) { 
    return 403; 
    } 
  #当通过mmdb数据库解析出$remote_addr中的ip对应的iso_code !=CN时返回403,或进入特定的页面或者网站
}
#搭配map,配置1
if ($allowed_country = yes) {
        return 403;
}
#搭配map,配置2
if ($allowed_country = no) {
        return 403;
}

配好后重启nginx就可以了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往日时光--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值