|||

网络攻防:Nginx只允许限定国家IP访问或登录

① 安装 GeoIP2 数据库(MaxMind)

1️⃣ 安装模块和工具

Ubuntu / Debian:

sudo apt update
sudo apt install -y libnginx-mod-http-geoip2 geoipupdate

2️⃣ 配置 MaxMind(国家库)

编辑配置:

sudo nano /etc/GeoIP.conf

填入(需要免费账号):

AccountID YOUR_ID
LicenseKey YOUR_KEY
EditionIDs GeoLite2-Country

然后下载数据库:

sudo geoipupdate

数据库一般在:

/usr/share/GeoIP/GeoLite2-Country.mmdb

② Nginx 配置:只允许 CN + JP

1️⃣ 在 http {} 里加 GeoIP 读取

http {
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        auto_reload 5m;
        $geoip2_country_code country iso_code;
    }

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

2️⃣ 在 server {} 里加访问控制

🔒 全站限制(最严格)

server {
    if ($allowed_country = 0) {
        return 444;
    }

    ...
}

444 = 直接断连接,对扫描器非常狠
(比 403 更不容易被重试)


🔐 只限制登录(更温和,推荐)

location ~ ^/(wp-login\.php|mylogin_970821) {
    if ($allowed_country = 0) {
        return 444;
    }

    limit_req zone=wp_login burst=3 nodelay;
    proxy_pass http://php-fpm;
}

这样效果是:

  • 国外 IP:连登录页都看不到
  • CN / JP:正常访问
  • 攻击日志会瞬间少 90%+

⚠️ 必须提前告诉你的现实问题

1️⃣ 中国 IP 不稳定(很重要)

  • 中国运营商 IP 变动频繁
  • MaxMind 对 CN 的识别 不是 100%
  • 偶尔会把中国 IP 识别成 HK / SG

👉 解决办法
如果你人在中国,建议加 HK 一起放行

HK 1;

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注