Nginx“auth_request”类似于速率限制的选项

时间:2017-09-30 12:46:23

标签: nginx

在Nginx中,我想向另一个检查速率限制违规的端点发送预请求。基本上正是auth_request所做的,但是auth_request只接受身份验证状态代码(200,401,403),我希望它只允许速率限制代码(200或429)。

是否有可用于此的auth_request更通用的版本?

目前我们正在使用auth_request,但缺点是将429个状态代码转换为500个。

谢谢!

1 个答案:

答案 0 :(得分:1)

以下配置适用于我并返回429而不是500

events {
    worker_connections  1024;
}
http {

   server {
      listen 80;

      location /api {
         auth_request /rate_limit;
         error_page 500 = @rate_limit_error;
         echo "You were allowed to access the API";
      }

      location @rate_limit_error {
          return 429 "Limit has been exceeded\n";
      }

      location = /rate_limit {
         internal;
         return 400 "Access is not allowed";
      }
   }
}

测试显示正确的响应

$ curl -v localhost/api?count=2
*   Trying ::1...
* Connected to localhost (::1) port 80 (#0)
> GET /api?count=2 HTTP/1.1
> Host: localhost
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 429
< Server: openresty/1.11.2.2
< Date: Sat, 30 Sep 2017 18:50:56 GMT
< Content-Type: text/plain
< Content-Length: 24
< Connection: close
<
Limit has been exceeded
* Closing connection 0

如果您不想返回消息或其他内容。您也可以使用error_page 500 = 429;