要限制恶意爬虫的访问频率,可以通过以下几种Nginx配置方法实现:
http {
limit_req_zone $binary_remote_addr zone=anti_spider:10m rate=1r/s;
server {
location / {
limit_req zone=anti_spider burst=5 nodelay;
# 其他配置...
}
}
}
zone=anti_spider:10m
创建10MB大小的共享内存区域存储访问状态rate=1r/s
限制每秒1个请求burst=5
允许短时间突发5个请求nodelay
对超出限制的请求立即返回503错误map $http_user_agent $bad_bot {
default 0;
~*(Googlebot|bingbot|YandexBot|Baiduspider|Sogou|Exabot|MJ12bot) 0;
~*(bot|crawl|spider|scrap|scan|grab|harvest) 1;
}
server {
if ($bad_bot) {
limit_req zone=anti_spider burst=5 nodelay;
}
# 其他配置...
}
geo $limited {
default 0;
123.123.123.123 1; # 恶意IP
124.124.124.124 1; # 另一个恶意IP
}
server {
if ($limited) {
limit_req zone=anti_spider burst=5 nodelay;
}
# 其他配置...
}
对于Nginx Plus用户,可以使用JWT验证来限制爬虫:
location / {
auth_jwt "Restricted";
auth_jwt_key_file /path/to/key.jwk;
# 其他配置...
}
http {
log_format anti_spider '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log anti_spider;
}
http {
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
server {
location / {
limit_conn conn_limit_per_ip 10;
# 其他配置...
}
}
}
nginx -s reload
以上方法可以单独使用,也可以组合使用以获得更好的防护效果。