Nginx 仅在某个位置限制 GET 或 POST 请求的速率

whi*_*ash 4 nginx rate-limiting nginx-location nginx-config

我在 nginx 中配置了一台服务器,并使用以下代码来创建我的速率限制区域:

limit_req_zone $key zone=six_zone:10m rate=60r/m;

在我的位置,我使用一个模块来满足请求。该位置支持 GET、POST 和 DELETE 方法。我正在尝试仅对对该位置的 GET 请求进行速率限制。我认为这可能有效,但事实并非如此。

location /api/ {
    if ($request_method = GET) {
        limit_req zone=six_zone;
    }
    reqfwder;
}
Run Code Online (Sandbox Code Playgroud)

对我如何解决这个问题有任何帮助或指示吗?谢谢。

小智 14

希望这可以帮助,

在 NGINX 配置的 http 上下文中,添加以下行:

http {
  ... # your nginx.conf here
  
  # Maps ip address to $limit variable if request is of type POST
  map $request_method $limit {
    default         "";
    POST            $binary_remote_addr;
  }
  
  # Creates 10mb zone in memory for storing binary ips
  limit_req_zone $limit zone=my_zone:10m rate=1r/s;
}

**Rate limiting for the entire NGINX process:**
http {
    ... # your nginx.conf here
    limit_req zone=global_zone;
}
Run Code Online (Sandbox Code Playgroud)

参考https://product.reverb.com/first-line-of-defense-blocking-bad-post-requests-using-nginx-rate-limiting-507f4c6eed7b