![图片[1]-Nginx 配置 GeoIP2 模块:只允许中国访问,屏蔽国外 IP(完整实战)-微生之最](https://cos.swszz.cn/2025/09/20250920164213423.webp)
在网站运维和服务器安全中,Nginx 只允许中国 IP 访问、屏蔽所有国外 IP 是一个非常常见的需求。
通过限制访问来源国家,可以有效:
- 减少境外恶意扫描与攻击
- 降低无效流量和带宽消耗
- 满足国内业务合规要求
- 提升网站整体访问性能
从网站访问统计数据可以看到,在未做限制前,美国等海外地区的访问次数往往占比最高,但这些流量对国内业务几乎没有价值。
本文将以 Nginx 1.29.0 为例,详细讲解如何:
- 编译安装 ngx_http_geoip2_module
- 使用 MaxMind GeoLite2 数据库精准识别 IP 国家
- 实现 Nginx 只允许中国访问,拦截所有国外 IP
一、准备工作
1️⃣ 确认 Nginx 版本
nginx -v
# nginx version: nginx/1.29.0
⚠️ 注意:GeoIP2 动态模块必须与 当前 Nginx 版本完全一致
2️⃣ 安装依赖(CentOS / Rocky / AlmaLinux)
yum install -y gcc make git wget \
libmaxminddb libmaxminddb-devel
二、下载并编译 ngx_http_geoip2_module
1️⃣ 下载 GeoIP2 模块源码
cd /tmp
git clone https://github.com/leev/ngx_http_geoip2_module.git
2️⃣ 下载对应版本的 Nginx 源码
wget https://nginx.org/download/nginx-1.29.0.tar.gz
tar -zxvf nginx-1.29.0.tar.gz
cd nginx-1.29.0
3️⃣ 编译为动态模块
./configure --with-compat \
--add-dynamic-module=/tmp/ngx_http_geoip2_module
make modules
4️⃣ 安装模块
cp objs/ngx_http_geoip2_module.so /usr/lib64/nginx/modules/
三、加载 GeoIP2 模块与数据库配置
1️⃣ 在 nginx.conf 顶部加载模块
load_module /usr/lib64/nginx/modules/ngx_http_geoip2_module.so;
2️⃣ 下载并放置 GeoLite2 数据库
mkdir -p /etc/nginx/geoip
# 上传并解压 GeoLite2-Country.mmdb
建议使用 GeoLite2-Country.mmdb,速度更快、够用
3️⃣ 在 http {} 中配置 GeoIP2
geoip2 /etc/nginx/geoip/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_country_code country iso_code;
$geoip2_country_name country names zh-CN;
}
map $geoip2_country_code $allowed_country {
default 0;
CN 1;
}
4️⃣ 访问日志(便于排查)
log_format geoip '$remote_addr [$geoip2_country_code $geoip2_country_name] '
'"$request" $status "$http_user_agent"';
四、Nginx 只允许中国访问(推荐写法)
推荐方式:不用 if,更安全稳定
server {
listen 80;
server_name yourdomain.com;
if ($allowed_country = 0) {
return 403;
}
location / {
root /data/wwwroot;
index index.html index.php;
}
}
访问效果
| 国家 | 访问结果 |
|---|---|
| 中国(CN) | ✅ 正常访问 |
| 国外 IP | ❌ 403 Forbidden |
五、Cloudflare 代理下获取真实 IP(重要)
如果你的网站使用了 Cloudflare CDN,必须设置真实客户端 IP:
real_ip_header CF-Connecting-IP;
# 只信任 Cloudflare 官方 IP(示例)
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
不要使用
set_real_ip_from 0.0.0.0/0;
否则存在安全风险。
六、常见问题汇总
GeoIP 数据库多久更新?
MaxMind 每周更新一次,建议配合 cron 定期替换 .mmdb 文件。
中文日志乱码?
export LANG=zh_CN.UTF-8
能不能允许多个国家?
map $geoip2_country_code $allowed_country {
default 0;
CN 1;
HK 1;
MO 1;
TW 1;
}
七、总结
通过 Nginx + ngx_http_geoip2_module + GeoLite2 数据库,我们可以非常高效地实现:
- Nginx 只允许中国访问
- 精准屏蔽国外 IP 流量
- 提升安全性、节省带宽、降低攻击风险
该方案广泛适用于:
- 国内业务站点
- WordPress / 企业官网
- API 接口防刷
- 服务器安全加固
© 版权声明
版权保护声明
尊重原创,保护知识产权
原创保护:本站所有原创内容均受著作权法保护,未经许可禁止转载或商业使用
转载规范:如需转载,请注明出处并保留原文链接,不得删改内容
免责声明:本站仅提供学习交流平台,内容观点不代表本站立场
侵权处理:如发现侵权内容,请及时联系我们,将在第一时间处理
THE END














暂无评论内容