HowTo: Nginx Block User Agent

Posted on in Categories last updated June 27, 2012

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
# /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:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

10 comment

  1. Question, is how to block a block that spoofs its user-agent, where it’s clear that the user agent is spoofed by the Comments token.
    i.e. the following user-agent string:
    “Mozilla/5.0 (compatible; ACHE/Unknown Version; +; )”
    Where we don’t want to be blocking by Mozilla/5.0, but rather want to be blocking by the entire string. (i.e. how to make the instruction look for “ACHE/Unknown Version” within the comments token of the user string.)

Leave a Comment