$request_length和$upstream_response_time是识别反代后端恶意请求最有效的切入点——前者暴露客户端原始报文大小,后者揭示后端是否被拖慢或卡死,两者叠加可快速区分正常调用、slowloris类慢速攻击及超大体填充攻击。

直接看 $request_length 和 $upstream_response_time 是识别反代后端恶意请求最有效的切入点——前者暴露客户端发来的原始报文大小,后者揭示后端是否被拖慢或卡死,两者叠加能快速区分正常调用、慢速攻击(如 Slowloris)和超大体填充类攻击。
必须显式记录关键长度与响应变量
默认日志格式不包含这些字段,需自定义 log_format 并确保在 proxy_pass 场景下生效:
- 务必加入
$request_length:它反映完整请求字节数(含 headers + body),对 POST/PUT 攻击极其敏感 - 必须包含
$upstream_response_time:仅当使用proxy_pass时才有值,数值异常高(如 >5s)往往意味着后端积压或被恶意阻塞 - 建议同时记录
$upstream_status和$status,用于区分是后端返回 504(超时)还是 Nginx 自身返回 502/503 - 示例配置(放在 http 块中):
log_format backend_probe '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '$request_length $upstream_response_time $upstream_status ' '"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/backend.log backend_probe;
从日志中识别三类典型反代攻击模式
结合字段组合分析,比单看请求数更精准:
- 超长报文填充攻击:$request_length > 2MB,但 $upstream_status 为 “-” 或 “000”,$upstream_response_time 极短(
- 慢速连接耗尽攻击:$request_length 很小(如几百字节),但 $upstream_response_time 异常长(>10s),且 $body_bytes_sent 极低 → 客户端缓慢发送 headers/body,占住 upstream 连接不释放
- 高频小包探测+打爆后端:同一 $remote_addr 在 60 秒内发起 >50 次 $request_length > 10KB 的 POST,$upstream_status 多数为 502/504,$upstream_response_time 分布离散 → 后端服务已不堪重负
用限流+标记机制实现自动拦截闭环
仅靠日志分析是被动的,需联动 Nginx 原生命令主动干预:
- 用
map标记高风险请求:
map $request_length $backend_attack_flag {
~^[5-9][0-9]{5,}$ 1; # ≥500KB
~^.*$ 0;
} - 基于标记构建限流区域:
limit_req_zone $binary_remote_addr$backend_attack_flag zone=backend_abuse:10m rate=5r/s; - 在 proxy location 中启用:
location /api/ {
limit_req zone=backend_abuse burst=10 nodelay;
proxy_pass http://upstream_cluster;
} - 补充防御:对 $upstream_response_time > 8s 的请求,可配合
proxy_next_upstream timeout error实现自动故障转移
验证与告警建议
拦截策略上线后,需持续验证有效性并建立轻量级告警:
- 用 awk 快速检查拦截效果:
awk '$12 > 524288 && $14 == "000" {print $1, $7, $12}' /var/log/nginx/backend.log | head -20(查超长且未转发请求) - 监控指标建议:
– 单 IP 每分钟 $request_length > 100KB 的请求数 > 30 次 → 触发限流日志告警
– $upstream_response_time P95 > 3s 且持续 5 分钟 → 告警后端性能恶化
– $upstream_status 以 “5” 开头的比例连续 2 分钟 > 5% → 判定为后端级故障或打爆攻击











