Nginx 高级 CC 与 DDoS 防御策略指南
一、分层防御体系架构
网络层防御 Nginx 应用层防御 后端资源保护 监控与响应
二、CC 攻击防御策略
1. 请求频率限制(核心防御)
nginx
# 在 http 块中定义限制区域
http {
# 定义请求限制区域
limit_req_zone $binary_remote_addr zone=req_perip:10m rate=10r/s;
limit_req_status 429; # 自定义限流状态码
# 定义并发连接限制
limit_conn_zone $binary_remote_addr zone=conn_perip:10m;
}
2. 关键位置应用限流
nginx
server {
# 登录接口严格限制
location = /login {
limit_req zone=req_perip burst=5 nodelay;
limit_conn conn_perip 3;
proxy_pass http://backend;
}
# API 接口限制
location /api/ {
limit_req zone=req_perip burst=10;
limit_conn conn_perip 5;
proxy_pass http://backend;
}
# 静态资源宽松限制
location ~* \.(js|css|png|jpg)$ {
limit_req zone=req_perip burst=20;
access_log off; # 减少日志压力
}
}
3. 人机验证挑战
nginx
location / {
# 当请求超过阈值时重定向到验证页面
error_page 429 = @verify;
limit_req zone=req_perip burst=15 nodelay;
# 正常请求处理
proxy_pass http://backend;
}
location @verify {
# 返回验证码挑战
add_header Content-Type text/html;
return 200 '<html><body>
<h1>请验证</h1>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js"></script>
<div class="cf-turnstile" data-sitekey="YOUR_SITE_KEY"></div>
</body></html>';
}
三、DDoS 防御策略
1. 连接限制配置
nginx
# 全局连接限制
events {
worker_connections 4096; # 根据服务器性能调整
}
http {
# 限制单个IP的连接数
limit_conn_zone $binary_remote_addr zone=conn_limit_perip:10m;
limit_conn conn_limit_perip 50;
# 限制每个连接的速率
limit_rate 500k; # 全局默认限速
# 限制请求体大小
client_max_body_size 10m;
}
2. 慢连接防护
nginx
http {
# 防止慢速攻击
client_body_timeout 10s; # 请求体超时
client_header_timeout 10s; # 请求头超时
keepalive_timeout 15s; # 保持连接超时
send_timeout 10s; # 发送响应超时
# 关闭不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
}
3. 高级防护模块
nginx
# 启用Nginx Plus或第三方模块
load_module modules/ngx_http_modsecurity_module.so;
load_module modules/ngx_http_geoip2_module.so;
http {
# 使用GeoIP限制地区访问
geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_country_code country iso_code;
}
map $geoip2_country_code $allowed_country {
default 0;
CN 1; # 只允许中国IP
US 1;
JP 1;
}
server {
# 应用地区限制
if ($allowed_country = 0) {
return 403;
}
# 启用WAF
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
}
四、Nginx 调优增强防御
1. 内核级优化 (sysctl.conf)
bash
# 防止SYN洪水攻击
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 4096
# 加快TIME-WAIT回收
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
# 连接追踪优化
net.netfilter.nf_conntrack_max = 1000000
net.netfilter.nf_conntrack_tcp_timeout_established = 1200
2. Nginx 工作进程优化
nginx
# 调整工作进程
worker_processes auto; # 自动匹配CPU核心
worker_rlimit_nofile 65535; # 每个进程最大文件描述符
# 使用多核处理连接
events {
use epoll;
worker_connections 4096;
multi_accept on;
}
3. 缓存优化减少后端压力
nginx
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
# 缓存锁定防止缓存击穿
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
}
}
五、云平台集成防御
1. 阿里云/腾讯云集成
nginx
# 通过HTTP头传递真实客户端IP
real_ip_header X-Forwarded-For;
set_real_ip_from 100.64.0.0/10; # 云平台内网段
# 启用云平台WAF
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 云平台特定头
proxy_set_header Ali-CDN-Real-IP $remote_addr;
proxy_set_header Qcloud-Real-IP $remote_addr;
}
2. Cloudflare 集成
nginx
# 只接受来自Cloudflare IP的请求
include /etc/nginx/cloudflare-ips.conf;
server {
listen 80;
server_name yourdomain.com;
# 仅允许Cloudflare IP访问
allow 103.21.244.0/22;
allow 103.22.200.0/22;
# ... 其他Cloudflare IP段
deny all;
location / {
proxy_pass http://backend;
}
}
六、监控与自动化响应
1. 实时监控配置
nginx
# 启用状态监控
server {
listen 127.0.0.1:8080;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
2. 自动封禁脚本
bash
#!/bin/bash
# 自动封禁高频IP
LOG_PATH="/var/log/nginx/access.log"
THRESHOLD=100 # 每分钟请求阈值
BAN_TIME=3600 # 封禁时间(秒)
tail -F $LOG_PATH | while read LINE
do
IP=$(echo $LINE | awk '{print $1}')
COUNT=$(grep $IP $LOG_PATH | wc -l)
if [ $COUNT -gt $THRESHOLD ]; then
# 添加到防火墙
iptables -A INPUT -s $IP -j DROP
# 定时解封
(sleep $BAN_TIME && iptables -D INPUT -s $IP -j DROP) &
fi
done
3. Prometheus + Grafana 监控面板
yaml
# nginx-prometheus-exporter 配置
scrape_configs:
- job_name: 'nginx'
static_configs:
- targets: ['nginx-host:9113']
metrics_path: /metrics
监控指标:
- 请求率
- 活动连接数
- 错误率
- 带宽使用
- 上游响应时间
七、应急响应计划
攻击发生时的处理流程:
-
启用紧急模式:
nginx# 在http块添加 limit_req_zone $binary_remote_addr zone=emergency:10m rate=5r/s; server { location / { limit_req zone=emergency burst=10 nodelay; } }
-
切换至静态维护页面:
nginxlocation / { root /var/www/emergency; try_files $uri /maintenance.html; }
-
启用云平台DDoS防护:
- 阿里云:启用DDoS高防IP
- 腾讯云:启用大禹BGP高防
- AWS:启用Shield Advanced
-
分析攻击模式:
bash# 分析访问日志 awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20 # 实时监控 tail -f access.log | grep -E ' (429|444|503) '
最佳实践总结
- 分层防御:网络层 + Nginx层 + 应用层
- 速率限制:基于IP和关键端点
- 连接管理:限制并发和超时
- 自动封禁:实时监控 + 自动响应
- 云平台集成:利用云WAF和DDoS防护
- 定期演练:每季度进行防御压力测试
关键建议:对于大规模DDoS攻击,建议结合云服务商的DDoS防护服务(如阿里云高防IP、Cloudflare Pro),这些服务提供TB级的清洗能力,远超单台Nginx服务器的防御能力。
最终部署前,务必进行压力测试:
bash
# 使用wrk进行压力测试
wrk -t12 -c400 -d30s --timeout 10s https://yourdomain.com
根据测试结果调整限流阈值和防护策略,确保在防护攻击的同时不影响正常用户访问。希望本篇文章能给你带来不一样的防御启发!