I'm looking into rate-limiting using nginx's HttpLimitReqModule. However, requests are all coming from the same IP (a loadbalancer), with the real IP address in the headers.

Is there a way to have nginx rate-limit based on the ip in the X-Forwarded-For header instead of the ip of the source?

  • Do not trust HTTP headers. It’s not something you can’t set to anything you want. May 31, 2021 at 21:11

2 Answers 2


Yes, typical rate-limiting configuration definition string looks like:

 limit_req_zone  $binary_remote_addr zone=zone:16m rate=1r/s;

where $binary_remote_addr is the unique key for limiter. You should try changing it to $http_x_forwarded_for variable which gets the value of X-Forwarded-For header. Although this will increase memory consumption because $binary_remote_addr is using compressed binary format for storing IP addresses and $http_x_forwarded_for is not.

 limit_req_zone  $http_x_forwarded_for zone=zone:16m rate=1r/s;

The limit_req_zone directive defines the variable to be used as key for request grouping.
Usually, the $binary_remote_addr is used rather than $remote_addr because it is smaller and saves space.

Maybe you alternatively want to use the RealipModule.
This will rewrite the remote address variables to the address provided in a custom header and will also make logging and other variable usage easier.

  • 1
    +1 for RealIP module. When using this module, $binary_remote_addr and $remote_addr are set to the value of your configured header, typically X-Forwarded-For - so your standard variables are now the "real client IP address". Run nginx -V to see if NGINX was built with --with-http_realip. Then config is as simple as: set_real_ip_from; real_ip_header X-Forwarded-For; , where the CIDR range is that of your upstream load balancer which is setting the X-Forwarder-For header. Jul 9, 2019 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.