如何使用 nginx 限制来自一个用户的请求数?

How to limit count of requests from one user with nginx?

我正在开发 rails 包含两个主要部分的应用程序:

Nginx 在生产中用作负载均衡器。 我如何向这些页面发出请求?

我想限制对这些页面的访问 - 一个用户每秒不超过 3 个请求:

如何更改 nginx.conf 以使其成为可能?

顺便说一句,如何更改 nginx.conf 来阻止爬虫和机器人?

(仅供 API 用户使用 api-访问权限)

谢谢。

在 nginx.conf 中编辑:

server {

  location ~ /product/show/(.*)\.json$ {
     limit_req zone=one burst=3;
     proxy_pass youturl/product/show/.json ; 
  }

  location /search/ {
     limit_req zone=one burst=3;
  }

}

或者看这里:http://nginx.org/en/docs/http/ngx_http_limit_req_module.html

我没有机会尝试,但是按照nginx的指导应该是这样的:

    location ~ /product/show/(.*)\.json$ {
    proxy_pass http://yoururl/product/show/.json ;
    limit_req zone=one burst=5;

}

作为与 Web 服务器无关的替代方案,您可以考虑机架攻击的节流功能 gem http://github.com/kickstarter/rack-attack#throttles

它的机架中间件,因此它会在 request/response 周期的早期拦截请求,但我猜它比纯粹使用 Nginx 模块要慢一点。 Kickstarter 等更大的项目使用它,因此它应该非常强大(参见 http://github.com/kickstarter/rack-attack#performance)。

至于不限制 API 用户,您可以在白名单块中完全忽略他们,方法是插入任何必要的逻辑来确认请求来自经过身份验证的 API user/client 会话(参见 https://github.com/kickstarter/rack-attack#whitelists)。