外观
CDN 或反代后的 Nginx 怎样识别并封禁客户端 IP
地址识别与封禁
CDNnginx封禁IP
2023-12-06
流量经 CDN 或反向代理到达 Nginx 时,后端看到的地址可能来自前置层。要按访客地址执行封禁,先让后端识别该地址。
配置文件放在哪里
- Nginx 的配置目录
/path/to/nginx/conf - 宝塔配置目录
/www/server/nginx/conf - Nginx 读取的主配置
/path/to/nginx/conf/nginx.conf - 宝塔环境主配置
/www/server/nginx/conf/nginx.conf - 虚拟主机配置示例
/path/to/nginx/conf/vhost/site.conf - 宝塔环境站点配置示例
/www/server/panel/vhost/nginx/site.conf
把地址识别和封禁规则分开写
waf_realip.conf用于还原客户端地址。waf_blacklist.conf存放要拦截的地址和网段。
两种实现方式
写法 A:real_ip + geo
- 适合按网段维护规则
- Nginx 的真实地址模块负责处理来源,geo 负责匹配封禁对象。
- 网段规则可采用 CIDR 表示。
- 兼容 IPv4 和 IPv6。
- 配置前的要求
- 要先维护前置层可信地址列表(
set_real_ip_from)。 - 首次启用时需先配好可信来源。
- 要先维护前置层可信地址列表(
写法 B(可用):map 解析 X-Forwarded-For + 规则匹配
下面是快速配置的示例。
map $http_x_forwarded_for $client_ip_from_xff {
default $remote_addr;
"~^\\s*(?<first>[^, ]+)" $first;
}按逗号取首项,对 IPv6 地址中的 :无额外限制,IPv4 也可使用。
在站点的 server 块中,可以从 $client_ip_from_xff 读取要匹配的地址。
if ($client_ip_from_xff ~* "^8\\.8\\.8\\.") {
return 403;
}- 配置特点
- 写法较短。
- 直接读取
X-Forwarded-For中的首个地址。
- 使用条件
- 只允许可信来源提供转发头,否则客户端可以伪造头里的地址。
- 如果需要长期维护较多 CIDR 规则,用
geo会更直观。 - 也要检查异常的
X-Forwarded-For取值。
配置 real_ip 与 geo
1) 创建 waf_realip.conf
,由 http 块载入。
# 只信任你的前置层(CDN 回源 IP 或反代机器 IP)
# 以下仅示例,请改成你自己的来源 IP 段。
set_real_ip_from 127.0.0.1;
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 172.16.0.0/12;
set_real_ip_from 192.168.0.0/16;
# 如果前置层透传的是 X-Forwarded-For
real_ip_header X-Forwarded-For;
real_ip_recursive on;前置层为 Cloudflare 时,可使用以下头字段。
real_ip_header CF-Connecting-IP;在 set_real_ip_from 中填 Cloudflare 公布的回源 IP 段。
如需核对识别结果,可在日志里记录还原后的地址。
log_format realip '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';2) 创建 waf_blacklist.conf
,可在 http 块声明封禁变量。
geo $ip_is_blocked {
default 0;
8.8.8.0/24 1;
8.8.8.8/32 1;
8.8.4.4/32 1;
}接着在该站点的 server 块把命中的请求拦下。
if ($ip_is_blocked) {
return 403;
}需要例外地址时,可另设白名单变量并让白名单优先。
geo $ip_is_allowed {
default 0;
1.2.3.4/32 1;
10.10.0.0/16 1;
}
if ($ip_is_allowed = 0) {
if ($ip_is_blocked) {
return 403;
}
}让主配置读取规则文件
打开 nginx.conf ,在其中的 http 块载入这两个文件。
include /path/to/nginx/conf/waf_realip.conf;
include /path/to/nginx/conf/waf_blacklist.conf;宝塔环境可使用下列路径。
include /www/server/nginx/conf/waf_realip.conf;
include /www/server/nginx/conf/waf_blacklist.conf;各配置在站点中的位置见下例。
http {
include mime.types;
default_type application/octet-stream;
include /www/server/nginx/conf/waf_realip.conf;
include /www/server/nginx/conf/waf_blacklist.conf;
server {
listen 80;
server_name example.com;
if ($ip_is_blocked) {
return 403;
}
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}先验证配置,再重载 Nginx
nginx -t
service nginx reload封禁规则未生效时
- 到访问日志里查看
remote_addr是否记录了客户端地址。 - 若
remote_addr仍显示 CDN 或反代的 IP,请检查set_real_ip_from和real_ip_header两处设置。 - 避免把
0.0.0.0/0等全量地址段列为可信来源,以防请求头被伪造。