Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block a specific user agent in nginx config

Tags:

nginx

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

like image 378
lordzouga Avatar asked Mar 03 '14 10:03

lordzouga


People also ask

How To block user agent in nginx?

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.


2 Answers

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.

like image 137
lordzouga Avatar answered Sep 27 '22 19:09

lordzouga


If's are evil - use the map directive.

See Nginx Ultimate Bad Bot Blocker

like image 23
Stuart Cardall Avatar answered Sep 27 '22 18:09

Stuart Cardall