HowTo: Nginx Block User Agent

by on April 29, 2012 · 5 comments· LAST UPDATED June 27, 2012

in

How do I block a http user agent or a software agent using Nginx web server under Linux or Unix like operating systems?

You can block any http user agents with GET / POST requests that scrape your content or try to exploit software vulnerability. Use the following syntax. Edit /usr/local/nginx/conf/nginx.conf file, enter:
# vi /usr/local/nginx/conf/nginx.conf
In this example, block http user agent called wget:

 
## Block http user agent - wget ##
if ($http_user_agent ~* (Wget) ) {
   return 403;
}
 
## Block Software download user agents ##
     if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
            return 403;
     }
 

Save and close the file. Reload nginx web server, enter:
# service nginx reload
OR
# /usr/local/nginx/sbin/nginx -s reload

How do I block multiple http user agents?

Use the following syntax:

 
if ($http_user_agent ~ (agent1|agent2|Foo|Wget|Catall Spider|AcoiRobot) ) {
    return 403;
}
 

Case insensitive blocking: ~* vs ~

Please note the ~* makes it case insensitive as opposed to just a ~:

 
### case sensitive http user agent blocking  ###
if ($http_user_agent ~ (Catall Spider|AcoiRobot) ) {
    return 403;
}
### case insensitive http user agent blocking  ###
if ($http_user_agent ~* (foo|bar) ) {
    return 403;
}
 

See also:

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 5 comments… read them below or add one }

1 sam November 1, 2012 at 6:56 pm

How do you put another condition instead of return? can you deny all and only allow a certain ip/subnet with those user agents to go through?

Reply

2 Sam November 1, 2012 at 8:49 pm

How do you put another condition instead of return? can you deny all and only allow a certain ip/subnet with those user agents to go through? any example?

Reply

3 cerb April 27, 2014 at 7:51 pm

i get the following error : “nginx: [emerg] “if” directive is not allowed here in /etc/nginx/nginx.conf:”
any thoughts?

Reply

4 Nigel May 7, 2014 at 1:57 pm

You need to make sure your if statement is in the server block.

Reply

5 cerb May 22, 2014 at 6:55 pm

Thanks Nigel, that did the trick.
its working perfectly now.

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: