Different limit_req rules for different user agents

Hello.

I need to check client’s user agent and apply different limit_req rules
for different UAs.
I’ve been trying to do it this way:

http {
limit_req_zone $binary_remote_addr zone=bots:10m rate=1r/m;
server {

location / {
if ($http_user_agent ~* (google|bing|yandex|msnbot) )
{
limit_req zone=bots burst=5 nodelay;
}
include balancer.conf;
}}}

But apparently I’m missing something as nginx -t says ‘[emerg]:
“limit_req” directive is not allowed here’. Most likely due to poor
understanding of configfile syntax. Please advice me on how to achieve
my goal.

Thanks in advance.

Posted at Nginx Forum:

On Monday 18 June 2012 15:14:12 LexxTheFox wrote:

location / {
if ($http_user_agent ~* (google|bing|yandex|msnbot) )
{
limit_req zone=bots burst=5 nodelay;
}
include balancer.conf;
}}}

http {

  map $http_user_agent $limit_bots {
      default '';
      ~*(google|bing|yandex|msnbot) $binary_remote_addr;
  }

  limit_req_zone $limit_bots zone=bots:10m rate=1r/m;

  server {
      location / {
          limit_req zone=bots burst=5 nodelay;
      }
  }

}

But apparently I’m missing something as nginx -t says ‘[emerg]:
“limit_req” directive is not allowed here’. Most likely due to poor
understanding of configfile syntax.

http://nginx.org/r/limit_req
context: http, server, location

wbr, Valentin V. Bartenev

Valentin V. Bartenev Wrote:

  server {
      location / {
          limit_req zone=bots burst=5 nodelay;
      }
  }

}

wbr, Valentin V. Bartenev

Hello.

I still don’t really get the ‘map’ magic. This example does not work for
me - bots still connect as often as they please. But your example gave
me an idea. After some reading and fiddling I managed to solve the
riddle this way:

http {
limit_req_zone $limit_bots zone=bots:10m rate=1r/m;
server {
location / {
set $bot ‘’;
if ($http_user_agent ~* (google|bing|yandex|msnbot) ) {set
$limit_bots $binary_remote_addr;}
limit_req zone=bots burst=5 nodelay;
}
}
}

I will continue reading docs and hope to figure everything out
eventually. By now it works for me.

Thank you for your help!

Posted at Nginx Forum: