25

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 Answer 1

20

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Would this work with header x-original-forwarded-for like this: map $http_x_original_forwarded_for $limit { default ""; "~.+" $binary_remote_addr; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.