Blocking requests in Nginx by User Agent

Often you can tell a request is up to no good, just by looking at the user agent. Rather than wait for Fail2Ban to block the IP, I setup a block list and reject the queries at Nginx.

Fail2Ban can still pickup the 403 logs and ban the IP, but why send any content.

In nginx.conf setup the list of user agents you want to block

http {
..........
  map $http_user_agent $block_ua {
      default 0;

      # Case-insensitive matching (~*) for specific bots or tools
      ~*nikto 1;
      ~*sqlmap 1;
      ~*scrapy 1;
      ~*python-requests 1;
      ~*curl 1;
      ~*wget 1;
      ~*Go-http-client 1;
      ~*python-urllib3 1;  
      ~*zgrab 1;
      ~*kx360-lane-a-widescan 1;
      ~*fastcrawl 1;

      # Block empty User-Agents
      "" 1;
  }
}

Then in your server block, return a 403 response

server {
  if ($block_ua) {
    return 403;
  }
}