nginx禁止国内IP访问网站

一、安装 geoip2 扩展依赖
## 编译安装
cd /usr/local/src
wget https://linuxhy.top/pptp/Nginx_Geoip2/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://linuxhy.top/pptp/Nginx_Geoip2/3.3.tar.gz
tar xf 3.3.tar.gz
mv ngx_http_geoip2_module-3.3 ngx_http_geoip2_module


或者在github下载
git clone https://github.com/leev/ngx_http_geoip2_module.git
三、安装 nginx 模块

1、安装依赖

yum -y install pcre-devel openssl-devel perl-devel libxml2

2、下载编译安装

cd /usr/local/src
wget https://nginx.org/download/nginx-1.20.2.tar.gz
tar xf nginx-1.20.2.tar.gz
cd nginx-1.20.2
./configure --prefix=/usr/local/nginx --user=root --group=root --with-file-aio --with-pcre --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_ssl_module --with-stream --add-module=/usr/local/src/ngx_http_geoip2_module
make
make install

扩展:
如果用 
./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这一步,不需要执行make install,make好以后,把 objs/nginx 拷贝到 /usr/local/nginx/sbin/nginx ,重新启动即可。

四、下载最新的 IP 地址数据库文件
cd /usr/local/nginx/conf/
mkdir geoip2
cd geoip2
wget https://linuxhy.top/pptp/Nginx_Geoip2/GeoLite2-master/GeoLite2-Country.mmdb
五、添加geoip访问策略

1、在 http 中添加 几行,定义数据库文件位置

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错误跳转至指定二级页面

    error_page 404 403 500  = https://error.xxx.com/;
    ....
}
六、重启nginx,并测试
pkill nginx
/etc/init.d/nginx start
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值