How to protect Nginx with a Fail2Ban jail

Create a Fail2Ban jail that monitors Nginx access and error logs to block brute-force and scanning attacks.

How to protect Nginx with a Fail2Ban jail

Create a Fail2Ban jail that monitors Nginx access and error logs to block brute-force and scanning attacks.

Prerequisites

  • Fail2Ban installed and running on a Linux server.
  • Nginx installed with access and error logging enabled.

Step-by-Step: Create an Nginx Jail in Fail2Ban

  1. Create or edit /etc/fail2ban/jail.local to add an Nginx authentication jail. Fail2Ban monitors the Nginx error log for repeated 401 (unauthorized) responses:

    [nginx-http-auth]
    enabled = true
    port = http,https
    filter = nginx-http-auth
    logpath = /var/log/nginx/error.log
    maxretry = 5
    findtime = 10m
    bantime = 1h
  2. Add a jail for blocking excessive 404 requests (scanners probing for vulnerabilities). Create a custom filter at /etc/fail2ban/filter.d/nginx-404.conf:

    [Definition]
    failregex = ^<HOST> - .* "(GET|POST|HEAD).* HTTP/.*" 404
    ignoreregex =
  3. Add the custom jail to jail.local:

    [nginx-404]
    enabled = true
    port = http,https
    filter = nginx-404
    logpath = /var/log/nginx/access.log
    maxretry = 10
    findtime = 5m
    bantime = 30m
  4. Restart Fail2Ban to activate the new jails:

    sudo systemctl restart fail2ban

How to Verify the Nginx Jails Are Active

Check the status of both jails:

sudo fail2ban-client status nginx-http-auth
sudo fail2ban-client status nginx-404