限制国外ip访问网站 1.安装带GeoIP模块的Nginxsudoaptupdatesudoaptinstallnginx-full-y安装后用 nginx -V 21 | 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_codecountry iso_code;}# ... 其他配置}在需要拦截的 server 或 location 块中通过 if 语句判断国家代码返回403禁止访问。例如以下配置只允许中国CN的IP访问其他国家则会被拒绝。server{listen80;server_name your-domain.com;if($geoip2_data_country_code!CN){return403;}# ... 其他配置}4.测试与验证完成配置后执行 sudo nginx -t 测试配置文件是否有语法错误。若显示 syntax is ok再执行 sudo systemctl reload nginx 平滑重载配置。可以通过VPN等工具更换到不同国家的IP进行访问测试。