Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 532
Pulkit Avatar asked Apr 15 '15 08:04

Pulkit


Video Answer


1 Answers

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;
like image 169
Tom Cannaerts Avatar answered Oct 09 '22 03:10

Tom Cannaerts