Fail2Ban Nginx Setup – Block Scanners and Exploits Without Blocking WordPress Admin

This guide shows a complete Fail2Ban installation and configuration for Nginx, designed to:

  • block real scanners and exploit attempts (e.g. requests to /.env, /.git, /phpmyadmin, etc.),
  • avoid blocking administrators by accident (common issue when banning only by HTTP errors),
  • ban IP addresses after repeated suspicious activity,
  • use a short ban time (5 minutes) to reduce the risk of locking yourself out.

Why banning by HTTP errors alone can backfire

Many guides suggest banning by HTTP status codes (4xx/499) only. In real life this often causes self-bans, because modern apps generate bursts of requests (AJAX, admin panels, cache rebuilds), and you can hit error statuses during normal work.

This setup uses a safer approach:

  • exploit paths are always suspicious,
  • HTTP errors are counted only when the request has no Referer (typical for scanners),
  • known bad User-Agents are counted.

Step 1: Install Fail2Ban

Install Fail2Ban:

Enable and start the service:

Verify that it is running:

Step 2: Create the nginx-secure filter

Create the filter file:

Paste the following configuration:

Step 3: Create the nginx-secure jail

Create the jail configuration file:

Paste the following configuration:

Step 4: Restart Fail2Ban

Step 5: Verify firewall integration

Check that the Fail2Ban chain exists:

External test

Run from another machine (exploit path test):

Test “errors without Referer” logic (scanner-like request – no referer header):

After repeated suspicious requests, the IP address will be banned for 5 minutes.

Check banned IPs

Unban IP address

Unban an IP manually:

Summary

  • blocks exploit paths and real scanners,
  • reduces self-bans by counting HTTP errors only when the Referer is missing,
  • uses a short 5-minute ban duration,
  • works with iptables-nft,
  • easy to test and easy to unban IP addresses.