简体   繁体   English

nginx中的速率限制基于http标头

[英]Rate limit in nginx based on http header

Maybe I am asking a poor question but I want to apply rate limit in nginx based on custom http header rather than IP based. 也许我问一个糟糕的问题,但我想在nginx中应用基于自定义http头而不是基于IP的速率限制。 My IP based configuration is working but I am not able to get around using custom http header. 我的基于IP的配置正在运行,但我无法使用自定义http标头。 What I want is that if a particular header is present in http request then rate limiting should be applied otherwise not. 我想要的是,如果http请求中存在特定标头,则应该应用速率限制,否则不应用。

conf file conf文件

       http {
            limit_req_zone $http_userAndroidId zone=one:10m rate=1r/s;

       location ^~ /mobileapp{
             set $no_cache 1;
             # set rate limit by pulkit
            limit_req zone=one burst=1;
            limit_req_status 429;
            error_page  429  /50x.html; 
      }
}

However, rate limiting is applied even if there is no header present. 但是,即使没有标题,也会应用速率限制。 PS userAndroidId is my request header. PS userAndroidId是我的请求标头。

I think you can manage this with map. 我想你可以用地图管理这个。 If the header is present, map a variable to either the IP of the client or to an empty string, and use that value as the key of the zone. 如果标头存在,则将变量映射到客户端的IP或空字符串,并将该值用作区域的键。 If the map does not match, the empty string will prevent rate limiting from happening. 如果映射不匹配,则空字符串将阻止速率限制的发生。

Something like this (not tested, but should work) 像这样的东西(未测试,但应该工作)

map $http_userandroidid $limit {
    default "";
    "~.+" $binary_remote_addr;
}

This will map an empty of missing userAndroidId header to "", and any other value to the $binary_remote_addr. 这会将空的缺少的userAndroidId标头映射到“”,并将任何其他值映射到$ binary_remote_addr。 You can then use the $limit variable in your zone like this: 然后,您可以在区域中使用$ limit变量,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM