Rate limit in nginx based on http header

2019-06-16 03:01发布

问题:

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;