大网数据广告活动
服务器运维问答

Nginx: Limit request based on response status code

· 52CE 我爱测

I'm trying to limit requests with nginx based on response status code. I'd like to slow down requests with too many 4xx or 5xx responses. I have this code block in my config file: map $status $bad_guy { ~^[23] ""; default $binary…

问题原文

原帖链接 · Viet Pham · CC BY-SA 3.0

I'm trying to limit requests with nginx based on response status code. I'd like to slow down requests with too many 4xx or 5xx responses. I have this code block in my config file:

map $status $bad_guy {
    ~^[23]  "";
    default $binary_remote_addr;
}
limit_req_zone "$bad_guy" zone=badguy:10m rate=1r/s;

server {
    limit_req zone=badguy burst=20;

It seems that the above config block all IP addresses sending more than 1 rps, including those with only 200 OK responses.

Could you help me please? Why do the above config not work? Do I have to use something else (maybe openresty?) to achieve this? Thank you.

社区高分解答

原帖链接 · finrod · CC BY-SA 4.0

This is quite tricky because the $status variable is empty when declaring the limit_req_zone. The $status is only known after nginx has processed the request. For example after a proxy_pass directive.

The closest I could get to achieve rate limiting by status is doing the following:

...
...
...
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
...
...
...
server {
    location /mylocation {
        proxy_intercept_errors on;
        proxy_pass http://example.org;
        error_page 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 421 422 423 424 426 428 429 431 451 500 501 502 503 504 505 506 507 508 510 511 @custom_error;
    }

    location @custom_error {
        limit_req zone=api burst=5 nodelay;
        return <some_error_code>;
    }

}
...

The drawback is that this way you must return a different status code then the proxy pass response.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-04-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。