13

How do I block a user agent using nginx. so far I have something like this:

if ($http_user_agent = "Mozilla/5.0 (Linux; Android 4.2.2; SGH-M919 Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.169 Mobile Safari/537.22") {
return 403;}

this is from a similar thread on this stack overflow.

I run nginx as a reverse proxy for cherrypy server. I intend to filter a certain user agent using nginx alone but the above code doesn't work on my server.

is that the correct way to do this? It wasn't included in any block in the nginx config. Should I add it to the "http" block or the "server" block

lordzouga
  • 549
  • 1
  • 5
  • 14

2 Answers2

27

in order to block the specific user agent I included this code in the "server" block:

if ($http_user_agent = "Mozilla/5.0 (Linux; Android 4.2.2; SGH-M919 Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.169 Mobile Safari/537.22"){
    return 403;
}

and it worked as expected.

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
lordzouga
  • 549
  • 1
  • 5
  • 14
8

If's are evil - use the map directive.

Directive if has problems when used in location context, in some cases it doesn’t do what you expect but something completely different instead. In some cases it even segfaults. It’s generally a good idea to avoid it if possible.

Nginx Ultimate Bad Bot Blocker makes blocking bots easy with support for Debian / Centos / Alpine Linux / FreeBSD.

Stuart Cardall
  • 2,099
  • 24
  • 18
  • Here's a good example of `map`ping: http://ask.xmodulo.com/block-specific-user-agents-nginx-web-server.html – admdrew Sep 10 '18 at 17:46
  • 11
    1. if's are only evil inside a location context. Not applicable here, this is on the server level. 2. Even if in location context, it is 100% safe to return a 403. So this is clearly a non-evil use of if. – geira Nov 12 '18 at 10:00
  • 2
    Introducing a dependency may be quite a bit more evil than carefully using something tricky once in a while. Especially something so huge and sophisticated yet not well known. Those "Easy Configutation Instructions" in 11 steps don't seem easy at all. – Gherman Aug 03 '20 at 13:21
  • @geira I wonder if these ifs can be used inside the "http" block, instead of the "server" block, so I could implement these Ifs ( rules ) globally and not host by host – Pablo Camara Dec 14 '20 at 02:30
  • Please explain some more. How would that look with the user agent above, returning a 403 to those? – luckydonald Jan 26 '21 at 01:33