限制国外ip访问网站
·
1.安装带GeoIP模块的Nginx
sudo apt update && sudo apt install nginx-full -y
安装后,用 nginx -V 2>&1 | grep geoip 检查是否包含相关模块。
2. 获取GeoIP数据库
访问 MaxMind官网 注册账号,登录后下载免费的 GeoLite2-Country.mmdb 文件。然后将数据库文件上传到服务器,例如 /etc/nginx/geoip/ 目录
3.配置Nginx拦截规则
在Nginx配置的 http 块中,添加 geoip2 配置,创建变量 $geoip2_data_country_code,它会存储来访IP的国家代码。
http {
geoip2 /etc/nginx/geoip/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
# ... 其他配置
}
在需要拦截的 server 或 location 块中,通过 if 语句判断国家代码,返回403禁止访问。例如,以下配置只允许中国(CN)的IP访问,其他国家则会被拒绝。
server {
listen 80;
server_name your-domain.com;
if ($geoip2_data_country_code != 'CN') {
return 403;
}
# ... 其他配置
}
4.测试与验证
完成配置后,执行 sudo nginx -t 测试配置文件是否有语法错误。若显示 syntax is ok,再执行 sudo systemctl reload nginx 平滑重载配置。可以通过VPN等工具更换到不同国家的IP进行访问测试。
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐

所有评论(0)