
This guide shows a complete Fail2Ban installation and configuration for Nginx and WordPress, designed to:
- block scanners and bots (e.g. attempts to access /.env, /.git, phpmyadmin, etc.),
- avoid blocking the WordPress administrator,
- ban IP addresses after 5 suspicious or invalid requests,
- apply only a 5-minute ban (no risk of locking yourself out for long).
Step 1: Install Fail2Ban
Install Fail2Ban:
|
1 2 |
apt update apt install -y fail2ban |
Enable and start the service:
|
1 2 |
systemctl enable fail2ban systemctl start fail2ban |
Verify that it is running:
|
1 2 |
fail2ban-client ping systemctl status fail2ban |
Step 2: Create the nginx-secure filter
Create the filter file:
|
1 |
nano /etc/fail2ban/filter.d/nginx-secure.conf |
Paste the following configuration:
|
1 2 3 4 5 6 7 8 9 10 |
[Definition] failregex = ^<HOST> - .* "(?:GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH|PROPFIND|CONNECT) (?:/\.env|/wp-config\.php|/phpinfo\.php|/(?:phpmyadmin|pma|adminer)(?:/|$)|/(?:\.git|\.svn|\.hg)(?:/|$)|/vendor/phpunit/|/cgi-bin/).*" \d{3} .* ^<HOST> - .* "(?:GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH|PROPFIND|CONNECT) (?!/(?:wp-login\.php|wp-admin/))[^"]*" (?:400|403|405|408|413|414|429|444|499) .* ^<HOST> - .* "(?:GET|POST|HEAD|PUT|DELETE|OPTIONS|PATCH|PROPFIND|CONNECT) .*" \d{3} .* "(?:[^"]*)" "(?:[^"]*(?:sqlmap|nikto|masscan|zgrab|nmap|acunetix|wpscan|dirbuster|gobuster)[^"]*)" .* ignoreregex = |
Step 3: Create the nginx-secure jail
Create the jail configuration file:
|
1 |
nano /etc/fail2ban/jail.d/nginx-secure.conf |
Paste the following configuration:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[nginx-secure] enabled = true port = http,https filter = nginx-secure logpath = /var/log/nginx/access.log /var/log/nginx/access-*.log findtime = 600 maxretry = 5 bantime = 300 action = iptables-multiport[name=nginx-secure, port="http,https"] ignoreip = 127.0.0.1/8 ::1 |
Step 4: Restart Fail2Ban
|
1 2 |
fail2ban-server -t systemctl restart fail2ban |
Step 5: Verify firewall integration
Check that the Fail2Ban chain exists:
|
1 2 |
iptables -S | grep f2b-nginx-secure iptables -L f2b-nginx-secure -n -v |
External test
Run from another machine:
|
1 2 3 |
for i in 1 2 3 4 5; do curl -I https://soban.pl/.env done |
After 5 attempts, the IP address will be banned for 5 minutes.
Check banned IPs
|
1 |
fail2ban-client status nginx-secure |
Unban IP address
Unban your IP manually:
|
1 |
fail2ban-client set nginx-secure unbanip YOUR_IP |
Summary
- protects against scanners and exploit attempts,
- does not block the WordPress admin panel,
- uses a short 5-minute ban duration,
- fully compatible with iptables-nft,
- easy to test and easy to unban IP addresses.