对令牌使用 NGINX 速率限制 [英] Use NGINX Rate Limiting with tokens

查看:73
本文介绍了对令牌使用 NGINX 速率限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 API 的访问限制为 10 个请求/秒.

I need to limit access to our API to 10 requests / second.

这是我根据他们的文档使用的区域:

This is the zone I'm using based on their documentation:

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

此区域使用用户 IP 地址作为标识来评估使用限制.通常,人们使用相同的 IP 地址访问我们的系统.

This zone uses the user IP address as identification to rate the usage limit. Often, people uses the same IP address to access our systems.

我想知道是否可以使用用户 tokenId 作为速率限制的标识.我们所有的请求都在 URL 中包含一个 tokenID 参数:www.example.com/api/events/?tokenID=*****.

I'm wondering if it's possible to use the user tokenId as identification for the rate limit. All of our requests contains a tokenID parameter in the URL: www.example.com/api/events/?tokenID=*****.

有什么线索吗?

谢谢.

更新

我尝试创建区域:limit_req_zone "$tokenid" zone=limit:10m rate=1r/s; (1 r/s 用于测试)并像这样提取 $tokenid 变量:

I tried creating the zone: limit_req_zone "$tokenid" zone=limit:10m rate=1r/s; (1 r/s for testing) and extracting the $tokenid variable like this:

limit_req_zone "$tokenid" zone=limit:10m rate=1r/s;

server {
   ...

   location ~ \.php {
      ...
      if ($args ~* "tokenID=([^&]+)") {
          set $tokenid "$1";
      }
      ...
   }
}

变量 $tokenid 确实包含确切的令牌(已测试向响应添加标头),但它似乎没有更新 limit_req_zone 使用的值.

The variable $tokenid does contain the exact token (tested adding a header to the response), but it does not seem to update its value used by limit_req_zone.

推荐答案

@TarunLalwani 提出的建议确实有效.

The suggestion made by @TarunLalwani actually works.

我应该使用 $arg_tokenID 而不是从 URI 中提取它并设置为变量.

I should use $arg_tokenID instead of extracting it from the URI and setting into a variable.

最终的配置文件如下所示:

The final config file looks like this:

limit_req_zone "$arg_tokenID" zone=limit:10m rate=10r/s;

server {
   ...
   limit_req zone=limit burst=10;
   ...
}

这篇关于对令牌使用 NGINX 速率限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆