试图获得在nginx中工作的以下行为
使用浏览器时,每个ip的默认速率限制为1r / s。 bing和google蜘蛛的速率限制为10r / s。 拒绝糟糕的机器人
不幸的是,谷歌不发布ip地址为googlebot,所以我只限于useragent。
到目前为止,
http { # Rate limits map $http_user_agent $uatype { default 'user'; ~*(google|bing|msnbot) 'okbot'; ~*(slurp|nastybot) 'badbot'; } limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; limit_req_zone $binary_remote_addr zone=two:10m rate=10r/s; ... server { ... location / { if ($uatype == 'badbot) { return 403; } limit_req zone=one burst=5 nodelay; if ($uatype != 'user') { limit_req zone=two burst=10 nodelay; } ... } ... } }
但是 – 如果不允许这样做。
$ nginx -t
nginx:[emerg]“limit_req”指令在/etc/nginx/nginx.conf里是不允许的nginx:configuration文件/etc/nginx/nginx.conftesting失败
在nginx论坛上有很多未经testing的build议,大多数甚至不会传递configtest。
一个看起来很有前途的是由推荐人提供的Nginx速率限制? – 该版本的缺点是,所有的configuration重复每个不同的限制(我有很多重写规则)
任何人都有好东西?
不幸的是你不能这样dynamic的,限制请求模块不支持这个。
你find的链接可能是实现这一目标的唯一方法。 使用include指令来“避免”重复您的configuration。
但是如果第三方的爬虫突然冒充了一个好的用户代理呢?
今天,我能够在用户代理基础上实现速率限制; 尝试这个:
map $http_user_agent $bad_bot { default 0; (foo|bar) 1; } map $http_user_agent $nice_bot { default ""; (baz|qux) 1; } limit_req_zone $nice_bot zone=one:10m rate=1r/s; limit_req_status 429; server { ... location / { limit_req zone=one nodelay; if ($badbot) { return 403; } ... } }