Nginx 配置 GeoIP2 模块:只允许中国访问,拦截国外 IP

Nginx 配置 GeoIP2 模块:只允许中国访问,拦截国外 IP

图片[1]-Nginx 配置 GeoIP2 模块:只允许中国访问,拦截国外 IP-微生之最

在网站运维中,很多站点需要 只对中国用户开放,而屏蔽所有国外访问,以减少无效流量、避免攻击和节省带宽。本文将详细介绍如何在 Nginx 1.29.0 上编译安装 ngx_http_geoip2_module 模块,并结合 MaxMind GeoLite2 数据库 实现精准的 IP 定位与访问控制。

从分析图上eo的数据统计可以看到,访问来源全球各地都有,在没有优化网站前美国的访问次数是最多的

一、准备工作

  • 确认 Nginx 版本
nginx -v
# nginx version: nginx/1.29.0
  • 安装依赖(以 CentOS/RHEL 为例)
yum install -y gcc make git wget libmaxminddb libmaxminddb-devel

二、下载并编译 GeoIP2 模块

  • 下载 GeoIP2 模块源码:
cd /tmp
git clone https://github.com/leev/ngx_http_geoip2_module.git
  • 下载与当前 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
  • 编译为动态模块:
./configure --with-compat --add-dynamic-module=/tmp/ngx_http_geoip2_module
make modules
  • 复制生成的 .so 模块:
cp objs/ngx_http_geoip2_module.so /usr/lib64/nginx/modules/

三、加载模块与配置 GeoIP2 数据库

  • /etc/nginx/nginx.conf 文件顶部增加:
load_module /usr/lib64/nginx/modules/ngx_http_geoip2_module.so;
  • 下载 MaxMind GeoLite2 数据库并解压到:
mkdir -p /etc/nginx/geoip
# 上传并解压 GeoLite2-City.mmdb / GeoLite2-Country.mmdb
  • http {} 段中增加配置:
geoip2 /etc/nginx/geoip/GeoLite2-Country.mmdb {
    auto_reload 5m;
    $geoip2_country_name country names en;
    $geoip2_country_code country iso_code;
}

map $geoip2_country_code $allowed_country {
    default 0;
    CN 1;
}

log_format main '$remote_addr $geoip2_country_name '
                '"$request" $status $body_bytes_sent "$http_user_agent"';

四、Nginx 只允许中国访问

在需要限制的 server {} 段中加入:

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        if ($allowed_country = 0) {
            return 403;
        }
    }
}

这样配置后:

  • 中国 IP (CN) → 正常访问
  • 其他国家 IP → 403 拒绝访问

六、常见问题

  • Cloudflare 代理导致 IP 不准确
real_ip_header CF-Connecting-IP;
set_real_ip_from 0.0.0.0/0;  # 建议填写 Cloudflare 官方 IP 段
  • 中文日志乱码
env LANG=zh_CN.UTF-8;
  • GeoIP 数据库更新

MaxMind 每周更新一次 GeoLite2 数据库,建议定期更新以保持准确性。

七、总结

通过 ngx_http_geoip2_module + MaxMind GeoLite2,我们可以轻松让 Nginx 实现 只允许中国 IP 访问,屏蔽所有国外流量,这种方式常用于:

  • 国内业务合规性要求
  • 防止境外恶意攻击和爬虫
  • 节省带宽,提升网站性能

THE END
喜欢就支持一下吧
点赞6 分享
微生的头像-微生之最
嘀哩 抢沙发

请登录后发表评论

    暂无评论内容