Rate limit in nginx based on http header

二次信任 提交于 2020-01-14 07:24:48

问题


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

       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. P.S. userAndroidId is my request header.


回答1:


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

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;


来源:https://stackoverflow.com/questions/29645390/rate-limit-in-nginx-based-on-http-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!