Nginx 屏蔽策略
在 Ubuntu 系统中,通过 Nginx 建立屏蔽机制可以从基础 IP 封禁、区域/国家封禁以及访问频率限制三个维度来实现。
以下是详细的操作步骤:
一、 封禁特定 IP 或 IP 段
这是最直接的方法,使用 Nginx 自带的 ngx_http_access_module 模块。
1. 直接在配置文件中封禁
编辑你的网站配置 文件(如 /etc/nginx/sites-available/default):
server {
listen 80;
server_name example.com;
# 封禁单个 IP
deny 123.123.123.123;
# 封禁整个 IP 段
deny 192.168.1.0/24;
# 允许特定 IP,其余全部封禁
allow 1.2.3.4;
deny all;
location / {
try_files $uri $uri/ =404;
}
}
2. 使用独立文件管理黑名单(推荐)
如果黑名单很长,建议新建一个文件 /etc/nginx/blockips.conf:
deny 1.1.1.1;
deny 2.2.2.2;
然后在主配置文件 nginx.conf 的 http 段落中引入:
http {
include /etc/nginx/blockips.conf;
...
}
最后重启 Nginx:sudo systemctl restart nginx
二、 限制 IP 访问频率(防 CC 攻击)
使用 ngx_http_limit_req_module 模块限制同一 IP 在单位时间内的请求数。
1. 定义限制规则
在 /etc/nginx/nginx.conf 的 http 块中定义:
http {
# 定义一个名为 "mylimit" 的共享内存区域,大小 10MB,频率为每秒 5 个请求
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=5r/s;
}
2. 应用限制规则
在 server 或 location 块中应用:
server {
location / {
# 使用定义的 mylimit 区域
# burst=10 表示超过频率后允许缓冲 10 个请求
# nodelay 表示不延迟,超过缓冲直接返回 503
limit_req zone=mylimit burst=10 nodelay;
proxy_pass http://backend;
}
}
三、 根据国家/地区封禁 IP (GeoIP2)
由于经典的 GeoIP 模块已过时,现在通用的是 MaxMind GeoIP2。
1. 安装模块和依赖
在 Ubuntu 上安装 GeoIP2 动态模块:
sudo apt update
sudo apt install libnginx-mod-http-geoip2
2. 下载数据库
你需要从 MaxMind 官网 注册免费账号并下载 GeoLite2-Country.mmdb,放到 /usr/share/GeoIP/ 目录下。
3. 配置 Nginx 识别国家
在 /etc/nginx/nginx.conf 的 http 块配置:
http {
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_data_country_code country iso_code;
}
# 使用 map 定义黑名单
map $geoip2_data_country_code $allowed_country {
default yes;
CN no; # 封禁中国
US no; # 封禁美国
}
}
4. 在 Server 中拦截
server {
if ($allowed_country = no) {
return 403; # 返回 403 禁止访问
}
}
四、 进阶:自动封禁(Fail2Ban)
如果想让系统自动识别恶意刷接口的 IP 并封禁,推荐使用 Fail2Ban。它会扫描 Nginx 日志,发现异常后通过 iptables 或 ufw 在防火墙层面封禁,效率比 Nginx 更高。
1. 安装 Fail2Ban
sudo apt install fail2ban
2. 配置规则
新建 /etc/fail2ban/jail.local:
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2
五、 总结与建议
- 少量固定 IP 封禁:直接用 Nginx 的
deny指令。 - 防止爬虫/轻量 CC:使用 Nginx 的
limit_req。 - 大面积区域封禁:使用
GeoIP2模块。 - 高并发攻击/自动化防御:必须配合 Ubuntu UFW 防火墙 或 Fail2Ban。
注意:修改完 Nginx 配置后,务必先测试配置是否正确:
sudo nginx -t
sudo systemctl reload nginx