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

nginx rate limit based on location & header of post

· 52CE 我爱测

Nginx has this useful module called ngx_http_limit_req_module where you can limit requests to the server based on IP or number of requests. Is it at all possible to rate limit the location that includes the custom header? e.g. I …

问题原文

原帖链接 · hookenz · CC BY-SA 3.0

Nginx has this useful module called ngx_http_limit_req_module where you can limit requests to the server based on IP or number of requests.

Is it at all possible to rate limit the location that includes the custom header? e.g. I tried this but it fails to start nginx.

location /myservice {
    if ($http_x_custom_header) {
      limit_req zone=one burst=5;
    }
}

The specific error is:

nginx: [emerg] "limit_req" directive is not allowed here in /etc/nginx/sites-enabled/default

i.e. it doesn't like the limi_req directive inside the if block. It's fine outside the if block.

I may be able to live with different set of limit parameters outside the location though.

已采纳解答

原帖链接 · Drifter104 · CC BY-SA 3.0

You are correct, limit_req can not be used at that level.

The way to get around that is as follows.

error_page 418 = @limitreq;

location /myservice {
    if ($http_x_custom_header) {
      return 418;
    }
}

location @limitreq {
    limit_req zone=one burst=5;
    <rest of config>
    }

This will return 418 if the custom_header is present, which nginx will intercept and send to the custom location block, which will the apply the limit_req

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

资料来源与适用范围

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

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

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