nginx中的速率限制基于http标头 [英] Rate limit in nginx based on http header

查看:165
本文介绍了nginx中的速率限制基于http标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我问一个糟糕的问题,但我想在nginx中根据自定义http标头而不是基于IP来应用速率限制。我的基于IP的配置正在运行,但我无法使用自定义http标头。我想要的是,如果http请求中存在特定标头,则应该应用速率限制,否则不应用。

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. My IP based configuration is working but I am not able to get around using custom http header. What I want is that if a particular header is present in http request then rate limiting should be applied otherwise not.

conf file

conf file

       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; 
      }
}

然而,即使没有,也会应用速率限制标题存在。
P.S. userAndroidId是我的请求标头。

However, rate limiting is applied even if there is no header present. P.S. userAndroidId is my request header.

推荐答案

我认为你可以用地图管理这个。如果标头存在,则将变量映射到客户端的IP或空字符串,并将该值用作区域的键。如果地图不匹配,空字符串将阻止限制发生。

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. 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;
}

这会将空的缺少的userAndroidId标头映射到,以及任何其他$ binary_remote_addr的值。然后,您可以在区域中使用$ limit变量,如下所示:

This will map an empty of missing userAndroidId header to "", and any other value to the $binary_remote_addr. You can then use the $limit variable in your zone like this:

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

这篇关于nginx中的速率限制基于http标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆