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

时间:2015-07-27 12:34:59

标签: ruby-on-rails security nginx

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

  • 获取/product/show/<product_id>.json路线
  • POST /search?query=<query> route

Nginx在生产时用作负载balanser。 如何向这些页面提出请求?

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

  • 用户应该每秒只能进行3次搜索
  • 用户应该每秒只能生成3个product.json请求

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

BTW,如何更改nginx.conf来阻止刮刀和机器人?

(仅限API用户使用api-access)

感谢。

3 个答案:

答案 0 :(得分:2)

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

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

对于非限制API用户,您可以通过插入确认请求来自经过身份验证的API用户/客户端会话所需的任何逻辑来完全忽略白名单块中的内容(请参阅https://github.com/kickstarter/rack-attack#whitelists)。

答案 1 :(得分:1)

在nginx.conf中编辑:

server {

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

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

}

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

答案 2 :(得分:1)

我没有机会尝试,但遵循nginx的指导原则应该如此:

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

}