保护Nginx服务器免受DDoS攻击需要多层次的安全策略组合,以下是从基础到高级的完整解决方案:
限制连接速率
http {
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
limit_conn conn_limit 10;
}
}
}
rate=10r/s
:限制每秒10个请求。burst=20
:允许突发20个请求排队。limit_conn
:限制单个IP的并发连接数。关闭非必要模块
autoindex
、SSI
等非必需模块以减少攻击面:./configure --without-http_autoindex_module --without-http_ssi_module
调整系统参数
# 防止SYN洪水
sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_max_syn_backlog=2048
启用Nginx缓存
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
}
}
使用Fail2Ban自动封禁IP
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
action = iptables-multiport[name=nginx, port="http,https"]
启用HTTP/2和Gzip
server {
listen 443 ssl http2;
gzip on;
gzip_types text/plain application/json;
}
Cloudflare防护
set_real_ip_from 103.21.244.0/22;
real_ip_header CF-Connecting-IP;
AWS Shield + WAF
快速切换至静态页
server {
location / {
error_page 503 = @maintenance;
if ($attack_condition) { return 503; }
}
location @maintenance {
root /var/www/static;
try_files /maintenance.html =503;
}
}
日志分析与实时监控
# 实时监控异常IP
tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
通过以上组合策略,可有效缓解从网络层(L3/L4)到应用层(L7)的DDoS攻击。实际部署时需根据业务流量模式调整阈值,并定期进行压力测试验证防护效果。