Step 1: Install Fail2ban (Debian/Ubuntu)
First, install Fail2ban by running:
sudo apt install fail2ban
Step 2: Navigate to the Fail2ban Directory
Change to the Fail2ban configuration directory:
cd /etc/fail2ban/
Step 3: Copy the Example Configuration File
Copy the example configuration file as a base for your custom configuration:
sudo cp jail.conf jail.local
Step 4: Create a New Filter
Navigate to the filter.d directory and create a new filter file:
cd filter.d/
sudo nano nginx-4xx.conf
Step 5: Define the Filter to Block Repeated 4xx Errors
Add the following content to the nginx-4xx.conf file:
[Definition]
failregex = ^<HOST>.*"(GET|POST|HEAD|CONNECT).*" (404|444|403|400) .*
ignoreregex = 127.0.0.1 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
Step 6: Edit the Jail Configuration to Use the New Filter
Go back to the previous directory and edit jail.local:
cd ..
sudo nano jail.local
Add the following section:
#
# Repeated 4xx errors (Nginx)
#
[nginx-4xx]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 4
Step 7: Restart Fail2ban for the Changes to Take Effect
Restart the Fail2ban service:
sudo systemctl restart fail2ban
Step 8: Check the Filter Status
Verify the filter is working:
sudo fail2ban-client status nginx-4xx
OR
For a prettified output:
sudo fail2ban-client get nginx-4xx banip | tr ' ' '\n'