http {
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
# 其他配置...
}
}
}
10r/s
表示每秒10个请求burst=20
允许突发20个请求nodelay
表示不延迟处理突发请求http {
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location / {
limit_conn conn_limit 5;
# 其他配置...
}
}
}
server {
if ($http_user_agent ~* (Scrapy|Curl|HttpClient|python-requests|wget|WinHTTP|X11|AhrefsBot|MJ12bot|SemrushBot|DotBot|Baiduspider|YandexBot|Sogou|Exabot|CCBot|PetalBot)) {
return 403;
}
# 其他配置...
}
location / {
deny 123.123.123.123;
deny 123.123.123.0/24;
allow all;
# 其他配置...
}
http {
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=2r/m;
server {
location = /login {
limit_req zone=login_limit burst=3 nodelay;
# 登录处理逻辑...
}
}
}
http {
geo $blacklist {
default 0;
include /etc/nginx/conf.d/blacklist.conf;
}
server {
if ($blacklist) {
return 403;
}
# 其他配置...
}
}
/etc/nginx/conf.d/blacklist.conf
中维护黑名单IPlocation /api/ {
# 检查请求是否包含有效token
if ($http_x_captcha_token != "your-secret-token") {
return 403;
}
# 其他配置...
}
log_format blocked '$time_local|$remote_addr|$http_user_agent|$request';
server {
location / {
access_log /var/log/nginx/blocked.log blocked if=$limit_req_status;
# 其他配置...
}
}
http {
# 定义限制区域
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=2r/m;
# 加载黑名单
geo $blacklist {
default 0;
include /etc/nginx/conf.d/blacklist.conf;
}
server {
# 基础防护
if ($blacklist) {
return 403;
}
if ($http_user_agent ~* (Scrapy|Curl|HttpClient|python-requests)) {
return 403;
}
location / {
limit_req zone=req_limit burst=20 nodelay;
limit_conn conn_limit 5;
# 其他配置...
}
location = /login {
limit_req zone=login_limit burst=3 nodelay;
# 登录处理逻辑...
}
# 记录被阻止的请求
access_log /var/log/nginx/blocked.log blocked if=$limit_req_status;
}
}
nginx -t
检查语法,然后 nginx -s reload
重新加载配置这些配置可以有效防止大多数恶意访问和简单爬虫攻击,但对于高级DDoS攻击或专业爬虫,可能需要结合云防护服务或专业安全解决方案。