# 阻止已知恶意爬虫和扫描器
if ($http_user_agent ~* (Scrapy|Curl|HttpClient|python-requests|Wget|Go-http-client|Java)) {
return 403;
}
# 允许主流浏览器访问
if ($http_user_agent ~* (Mozilla|Chrome|Safari|Firefox|Edge|Opera)) {
break;
}
# 限制单个IP的请求频率
limit_req_zone $binary_remote_addr zone=req_perip:10m rate=10r/s;
limit_req zone=req_perip burst=20 nodelay;
# 阻止连续快速请求
if ($request_method = GET) {
set $rule_0 1;
}
if ($uri ~* "\.(jpg|png|gif|css|js)$") {
set $rule_0 0;
}
if ($http_referer = "") {
set $rule_0 "${rule_0}1";
}
if ($rule_0 = "11") {
return 403;
}
# 对可疑请求重定向到验证码页面
location / {
if ($http_cookie !~* "human=verified") {
return 302 /captcha.html;
}
# 正常处理请求
}
# 限制单个IP的连接数
limit_conn_zone $binary_remote_addr zone=conn_perip:10m;
limit_conn conn_perip 20;
# 限制客户端下载速度
limit_rate 100k;
limit_rate_after 1m;
# 使用GeoIP模块限制特定国家访问
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
CN yes;
US yes;
# 其他允许的国家
}
server {
if ($allowed_country = no) {
return 403;
}
}
# 启用SYN Cookie防护
net.ipv4.tcp_syncookies = 1
# 减少SYN+ACK重试次数
net.ipv4.tcp_synack_retries = 2
# 启用TCP连接追踪
net.netfilter.nf_conntrack_max = 1048576
# 高级请求速率限制
limit_req_zone $binary_remote_addr zone=ddos:10m rate=100r/s;
limit_req zone=ddos burst=200 nodelay;
# 连接耗尽防护
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_conn conn_limit 50;
客户端 → CDN防护 → WAF防火墙 → Nginx基础防护 → 应用层防护
# 详细日志记录
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$http_x_forwarded_for';
access_log /var/log/nginx/security.log security;
#!/bin/bash
# 自动封禁频繁访问的IP
tail -n 10000 /var/log/nginx/access.log | \
awk '{print $1}' | \
sort | \
uniq -c | \
sort -nr | \
awk '{if($1 > 100) print "iptables -A INPUT -s " $2 " -j DROP"}' | \
sh
以上策略需要根据实际业务需求和安全评估进行调整,过度防护可能影响正常用户访问。