---
title: "nginx rate limiting with a combination of IP and user agent"
date: 2016-09-07
updated: 2026-09-26
canonical: https://michaelshadle.com/2016/09/07/nginx-rate-limiting-with-a-combination-of-ip-and-user-agent
---

# nginx rate limiting with a combination of IP and user agent

Here's a quick and dirty way to use IP-based rate limiting (very common) but override it for specific user agents (or basically, this is just a method of chaining `geo` and `map` and other things together - you have to recycle the variables as each following statement's `default` value.

```
# whitelisted IP ranges - will not have limits applied
geo $geo_whitelist {
  default 0;
  1.2.3.4 1;
  2.3.4.5/24 1;
}

# whitelisted user agents - will not have limits applied
map $http_user_agent $whitelist {
  default $geo_whitelist;
  ~*(google) 1;
}

# if whitelist is 0, put the binary IP address in $limit so the rate limiting has something to use
map $whitelist $limit {
  0 $binary_remote_addr;
  1 "";
}

limit_req_zone $limit zone=perip:30m rate=1r/s;
```

References:
- [http://serverfault.com/questions/177461/how-to-rate-limit-in-nginx-but-including-excluding-certain-ip-addresses](http://serverfault.com/questions/177461/how-to-rate-limit-in-nginx-but-including-excluding-certain-ip-addresses)
- [http://stackoverflow.com/a/30083902](http://stackoverflow.com/a/30083902)
