Website Vidya
SecurityStep-by-Step Guide

How to Secure Nginx Server with Fail2Ban on Ubuntu Server

Learn how to secure Nginx server with Fail2Ban on Ubuntu with custom jails, regex filters, UFW integration, IP whitelisting, and monitoring.

RR
Rajesh RayLead Systems Educator
Published:
6 min read
PDF Cheat Sheet
How to Secure Nginx Server with Fail2Ban on Ubuntu Server
AI Executive SummaryCORE CIS AI

6 min read

Learn how to secure Nginx server with Fail2Ban on Ubuntu with custom jails, regex filters, UFW integration, IP whitelisting, and monitoring.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing Fail2Ban and Verifying Systemd Service Status
  • Step 2: Creating a Persistent jail.local Configuration File
Grounded in full engineering runbookCORE CIS Ai Engine

Interactive Builder for this Guide

Build your custom firewall syntax (How to Secure Nginx Server with Fail2Ban on Ubuntu Server)

Generated POSIX Command
sudo ufw allow port 443 proto tcp comment 'Production HTTPS'
UFW rule to ALLOW port 443/tcp.
Flag-by-Flag Breakdown
ufw allowallow matching inbound packets
port 443Match destination port 443
proto tcpFilter TCP transport traffic

Public-facing web applications are subjected to non-stop automated attacks, including brute-force HTTP authentication attempts, WordPress script scans, and denial-of-service request floods. When you configure and secure nginx server with fail2ban on ubuntu, you establish an automated intrusion prevention layer that continuously inspects server access and error logs, detects abusive traffic patterns, and dynamically drops malicious client IP addresses at the firewall layer.

Fail2Ban functions by pairing regex filter definitions with jail policies. Whenever an offending IP address generates more failures than your configured threshold within a specific timeframe, Fail2Ban immediately injects a temporary or permanent drop rule into your Linux packet filtering system (such as UFW or iptables/nftables). This hardening tutorial walks you through production setup, IP whitelisting, custom log filters, and ban management.

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Advertisement

Before proceeding, ensure you have the following requirements satisfied:

  • An active Ubuntu Server installation running Nginx as a reverse proxy or web server.
  • A user account with active sudo administrative privileges.
  • An operational firewall (UFW) configured and enabled on your server.
  • Standard Nginx access and error logging enabled under /var/log/nginx/.

Step 1: Installing Fail2Ban and Verifying Systemd Service Status

Upon installation, Fail2Ban creates its configuration hierarchy under /etc/fail2ban/ and automatically starts in the background using systemd.

# Update package metadata and install Fail2Ban
sudo apt update
sudo apt install -y fail2ban

# Verify that the Fail2Ban service is active and running
sudo systemctl status fail2ban

Step 2: Creating a Persistent jail.local Configuration File

The default configuration file /etc/fail2ban/jail.conf should never be edited directly. Package updates will overwrite changes made to jail.conf. Instead, create a dedicated override file named jail.local.

Fail2Ban reads jail.conf first, then merges and applies any modifications defined in jail.local.

# Copy the base jail file to create your custom local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Open jail.local in your preferred text editor
sudo nano /etc/fail2ban/jail.local

Step 3: Configuring Global Defaults and Administrator IP Whitelisting

Setting banaction = ufw instructs Fail2Ban to execute ufw insert 1 deny from <ip> instead of low-level iptables rules, ensuring all ban actions are visible when checking sudo ufw status.

Advertisement
[DEFAULT]
# Whitelist trusted administrative IP addresses and CIDR subnets
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24 203.0.113.45

# Time duration for which an offending IP remains banned (e.g., 1 hour)
bantime  = 1h

# Window of time during which failed attempts are counted
findtime = 10m

# Number of failed attempts permitted before triggering a ban
maxretry = 5

# Integrate directly with Ubuntu's Uncomplicated Firewall (UFW)
banaction = ufw

Step 4: Enabling Native Nginx Security Jails

Notice how each jail specifies the appropriate log file: nginx-http-auth inspects error.log for 401 unauthorized errors, while nginx-botsearch inspects access.log for probes targeting sensitive URIs like wp-login.php or .env.

[nginx-http-auth]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 3
bantime  = 1d

[nginx-botsearch]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 2
bantime  = 7d

[nginx-bad-request]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 3
bantime  = 1d

[nginx-limit-req]
enabled  = true
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 5
bantime  = 2h

Step 5: Creating Custom Regex Filters for Proactive Probing Defense

Automated vulnerability scanners constantly crawl web servers searching for vulnerable PHP scripts, exposed database administrative portals, and configuration backups. You can define a custom filter to detect and ban these scanners after minimal attempts.

Create a new filter definition file named /etc/fail2ban/filter.d/nginx-custom-probe.conf.

# Create custom filter file
sudo nano /etc/fail2ban/filter.d/nginx-custom-probe.conf

Defining failregex Patterns for Malicious Scanners

Add the following regex definition to detect common malicious URI probes:

[Definition]
failregex = ^<HOST> -.*"(GET|POST|HEAD) /(wp-admin|wp-login.php|xmlrpc.php|.env|.git|phpmyadmin|pma|config.json) HTTP/.*" (403|404) .*$

ignoreregex =

Activating the Custom Jail in jail.local

Append the new custom jail configuration to your /etc/fail2ban/jail.local file.

Advertisement
[nginx-custom-probe]
enabled  = true
port     = http,https
filter   = nginx-custom-probe
logpath  = /var/log/nginx/access.log
maxretry = 2
findtime = 10m
bantime  = 30d

Step 6: Testing Filter Expressions with fail2ban-regex

If the test confirms positive matches, reload Fail2Ban to apply your configuration changes.

# Test custom filter regex against the current access log
sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-custom-probe.conf

# Sample output:
# Results
# =======
# Failregex: 14 total
# |-  #) [# of hits] date time host
# |   1) [14] Mon Oct 23 18:22:10 198.51.100.24
# Info: Success! Matched 14 lines.

Step 7: Applying Changes and Managing Bans with fail2ban-client

Restart or reload the Fail2Ban systemd service to activate the configured jails.

Use the fail2ban-client command-line utility to monitor jail operation, verify active bans, or manually unban IP addresses.

# Restart Fail2Ban to load all new jails
sudo systemctl restart fail2ban

# Check the global status and list all running jails
sudo fail2ban-client status

# Output sample:
# Status
# |- Number of jail:      5
# `- Jail list:          nginx-bad-request, nginx-botsearch, nginx-custom-probe, nginx-http-auth, nginx-limit-req

Inspecting Jail Metrics and Unbanning Addresses

To check currently banned IP addresses within a specific jail, execute the status command for that jail.

# Inspect bans in the custom probe jail
sudo fail2ban-client status nginx-custom-probe

# Manually ban an abusive IP address immediately
sudo fail2ban-client set nginx-custom-probe banip 198.51.100.99

# Manually unban an IP address that was blocked accidentally
sudo fail2ban-client set nginx-custom-probe unbanip 198.51.100.99

Step 8: Verifying UFW Firewall Rules and Ban Persistence

When an IP address triggers a ban, Fail2Ban communicates with UFW to drop packets from that address. Verify that UFW reflects the active ban rules.

Check UFW status with verbose output to inspect active drop targets.

# Inspect active UFW firewall rules
sudo ufw status verbose

# Expected sample output showing injected Fail2Ban bans:
# Status: active
# To                         Action      From
# --                         ------      ----
# Any                        DENY        198.51.100.24
# 80/tcp                     ALLOW IN    Anywhere
# 443/tcp                    ALLOW IN    Anywhere

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

Fail2Ban fails to start with 'Found no accessible log files' error.

Cause: The configured logpath does not exist or has restrictive file permissions preventing Fail2Ban from reading it.

Resolution: Verify that Nginx is running and creating logs under /var/log/nginx/. Ensure the directory permissions allow read access.

ls -la /var/log/nginx/

Client IP addresses behind Cloudflare or reverse proxy are all showing as proxy IPs.

Cause: Nginx logs the upstream proxy IP instead of the original client IP provided in the X-Forwarded-For HTTP header.

Resolution: Configure Nginx with set_real_ip_from and real_ip_header X-Forwarded-For in /etc/nginx/nginx.conf so access logs record the real client IP.

sudo nginx -t && sudo systemctl reload nginx

Banned IP addresses can still establish new connections.

Cause: The banaction in jail.local is misconfigured or existing established connections are not reset by the firewall.

Resolution: Ensure banaction = ufw is set under [DEFAULT] and verify that UFW is enabled and active (sudo ufw status).

sudo ufw enable

Security Best Practices and Hardening

Always include your own public IP address and internal management subnets in ignoreip before activating aggressive jails.

Pair Fail2Ban with rate limiting and automated log rotation (logrotate) to ensure log files do not exhaust disk storage.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
No. Fail2Ban parses log entries asynchronously in the background. It does not intercept incoming HTTP traffic or add latency to Nginx web request processing.
Fail2Ban stores active ban history in a local SQLite database located at /var/lib/fail2ban/fail2ban.sqlite3. When the server reboots, Fail2Ban automatically restores all active unexpired bans to the firewall.
You can set bantime = -1 in a specific jail to make bans permanent, or set an extended ban duration such as bantime = 90d. Alternatively, add a permanent drop rule directly to UFW: sudo ufw insert 1 deny from <ip>.
Yes, but you must either mount host log directories into the container or configure Fail2Ban on the host system to monitor the container's exported log volumes and manage the host firewall.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Uncategorized•

How to Redirect HTTP to HTTPS in Nginx

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout