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
The ~ operator does case-sensitive matching against user-agent string, while the ~* operator does case-insensitive matching. The | operator is logical-OR, so you can put as many user-agent keywords in the if statements, and block them all. You can test user-agent blocking by using wget or curl with --user-agent option.
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.
If's are evil - use the map
directive.
See Nginx Ultimate Bad Bot Blocker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With