Layer 7 DDoS Mitigation on Linux: nginx limit_req & fail2ban
Layer 7 DDoS mitigation on a Linux web server comes down to three things: limit how fast each client can send requests, drop slow or abusive connections early, and ban repeat offenders automatically. nginx limit_req, limit_conn and tight timeouts handle the first two, and fail2ban handles the third. None of this helps once the attack fills your uplink, because the packets never reach nginx. That is where flow-based detection and upstream protection take over.
This guide covers the host-level layer first, then shows how to recognize the point where the problem stops being an application problem.
What a layer 7 flood looks like
Application-layer attacks use complete, valid TCP handshakes and often valid TLS. Bandwidth can be modest. The damage comes from CPU, PHP workers, database connections or file descriptors running out.
| Attack | Symptom | First control |
|---|---|---|
| Request flood (GET/POST to expensive URLs) | High CPU, PHP-FPM pool full, 502/504 errors | limit_req |
| Slowloris / slow POST | Many connections open, almost no traffic | Timeouts, limit_conn |
wp-login.php brute force |
POST spikes, 200/401 responses | Tight limit_req, fail2ban |
xmlrpc.php abuse (system.multicall, pingback) |
Many POSTs, high PHP load | Block the file or rate limit |
Step 1: Confirm it is layer 7
Before changing configs, look at the evidence. Check the interface rate and the connection states:
# Packet and bit rate per interface (1-second samples)
sar -n DEV 1 5
# Connection states
ss -s
ss -tn state established '( dport = :443 )' | wc -l
If the NIC is nearly idle but nginx workers are busy, you have an application problem. If rx pps or bps is high and the CPU is spent in softirq, skip ahead to the volumetric section.
Step 2: Find the offenders in the logs
Use a log format that records what you need. Add the request time and the upstream time so you can tell which URLs hurt:
log_format main_rt '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/access.log main_rt;
Then run quick one-liners against the current log:
# Top client IPs
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
# Top requested URLs
awk '{print $7}' access.log | sort | uniq -c | sort -rn | head -20
# Top user agents
awk -F'"' '{print $6}' access.log | sort | uniq -c | sort -rn | head -10
# WordPress login/xmlrpc POSTs per IP
grep -E 'POST /(wp-login|xmlrpc)\.php' access.log \
| awk '{print $1}' | sort | uniq -c | sort -rn | head
Look for a few IPs with huge counts (simple flood), or thousands of IPs with a handful of requests each to the same URL (distributed). The second pattern means per-IP limits alone will not be enough.
Step 3: nginx rate limiting with limit_req
limit_req implements a leaky bucket per key, usually the client IP. Define the zones in the http block:
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=30r/m;
limit_conn_zone $binary_remote_addr zone=connperip:10m;
limit_req_status 429;
limit_conn_status 429;
Apply them in the server block:
server {
listen 443 ssl;
server_name example.com;
limit_req zone=perip burst=20 nodelay;
limit_conn connperip 20;
location = /wp-login.php {
limit_req zone=login burst=5 nodelay;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php-fpm.sock;
}
# Block it entirely if you do not use XML-RPC (Jetpack and some mobile apps do)
location = /xmlrpc.php {
return 403;
}
}
Notes that save you pain:
burstabsorbs legitimate bursts such as a browser loading 15 assets at once. Without it, normal users get 429s.nodelayserves burst requests immediately and rejects the excess. Without it, nginx queues them, which holds connections open.- Use
limit_req_dry_run on;(nginx 1.17.1+) to log what would be rejected before you enforce it. - Apply stricter limits to expensive endpoints (search, login, checkout, API) rather than only a global limit. Static files can have a much higher limit or none.
Step 4: Slowloris and slow POST
Slowloris keeps connections open by sending headers or bodies very slowly. nginx's event-driven design handles this better than process-per-connection servers, but it still runs out of connections and file descriptors. Tighten the timeouts:
client_header_timeout 10s;
client_body_timeout 10s;
send_timeout 15s;
keepalive_timeout 15s;
reset_timedout_connection on;
client_max_body_size 10m;
large_client_header_buffers 4 8k;
Also check worker_connections and the file descriptor limit (worker_rlimit_nofile). limit_conn connperip 20 stops a single IP from holding hundreds of connections. If you serve many users behind carrier-grade NAT or an office proxy, raise it or you will block real users.
Step 5: Ban repeat offenders with fail2ban
Rate limiting returns 429, but the client keeps sending. fail2ban reads the logs and adds the IP to a firewall set, so those requests stop costing nginx anything. fail2ban ships a filter named nginx-limit-req that reads the nginx error log. Add a custom filter for WordPress abuse:
# /etc/fail2ban/filter.d/nginx-wp-abuse.conf
[Definition]
failregex = ^<HOST> .* "POST /(wp-login\.php|xmlrpc\.php)[^"]*" (200|401|403|429)
ignoreregex =
# /etc/fail2ban/jail.d/nginx.local
[nginx-limit-req]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 10
findtime = 60
bantime = 1h
banaction = nftables-multiport
[nginx-wp-abuse]
enabled = true
port = http,https
filter = nginx-wp-abuse
logpath = /var/log/nginx/access.log
maxretry = 8
findtime = 120
bantime = 6h
banaction = nftables-multiport
Test the filter before relying on it:
fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-wp-abuse.conf
fail2ban-client status nginx-wp-abuse
fail2ban is reactive. It parses log files, so there is a delay of seconds, and it burns CPU on huge logs. It suits brute force and moderate floods, not thousands of distinct source IPs.
Common mistakes
- Wrong client IP behind a proxy or CDN. If nginx sits behind a load balancer,
$remote_addris the proxy, and you will rate limit or ban everyone at once. Configureset_real_ip_fromandreal_ip_header X-Forwarded-For;for trusted proxies only. fail2ban needs the real IP in the log too. - Banning your own monitoring or payment webhooks. Add them to
ignoreipand exempt them from limits. - Using the same limit for every URL. A limit that protects
/wp-login.phpis far too tight for a page with many assets. - Trusting
X-Forwarded-Forfrom the internet. Attackers can forge it. - Skipping dry-run. Enforce a new limit blind and you can cause your own outage.
- Relying on a host firewall during a bandwidth flood. By the time packets reach iptables or nftables, the link is already full.
When the attack becomes volumetric
Signs that you have outgrown host-level controls:
- The uplink or the router port is saturated while nginx logs show far fewer requests than you would expect.
- Rx pps is high and softirq CPU is high, with
nf_conntrackor SYN backlog pressure. - Thousands of source IPs, each below any sensible per-IP limit.
- Mixed traffic, such as an HTTP flood combined with a UDP or SYN flood against the same IP.
At this point, you need visibility at the network edge, not the web server. Export NetFlow v5/v9, IPFIX or sFlow from your border routers to a collector, and set per-destination-IP bps and pps thresholds so you know which host is targeted within seconds. A flow-based detector such as NixMon does this and can trigger a BGP blackhole (RTBH) or a BGP FlowSpec rule. If you run FastNetMon or another collector, the same principle applies. Evaluate how fast it detects and which actions it can automate.
Understand what flow data can and cannot do. Flows show addresses, ports, protocols and volume, not URLs or HTTP headers. A pure HTTPS request flood that does not move the bandwidth needle will not show up in flows, so layer 7 controls remain your answer to that. Flow detection is for the part that fills pipes.
Your mitigation options for the volumetric part, from blunt to precise:
- RTBH. Blackhole the victim /32 (for example 192.0.2.10/32) toward your upstream. It stops collateral damage on your link but also takes the victim offline, so use it as a last resort.
- FlowSpec. Filter by protocol, port or packet size when the attack has a clear signature. It does not help much against HTTPS floods that look like real traffic.
- Upstream scrubbing. Your prefixes are announced from a scrubbing edge, and only clean traffic returns to you. For networks with their own ASN and at least one /24, NixGuard Edge does this by announcing your prefixes from the edge and delivering clean traffic over a GRE tunnel with a BGP session inside. It can run always-on or on-demand.
A practical layered setup
- nginx: per-IP and per-endpoint
limit_req,limit_conn, short timeouts, real client IP handling. - fail2ban: ban repeat offenders into nftables.
- Edge routers: flow export to a detector with per-IP thresholds.
- Automated RTBH or FlowSpec for known signatures.
- Upstream scrubbing for attacks that exceed your transit capacity.
Test each layer. Replay a load test against a staging host with limit_req_dry_run first, then confirm that a ban actually appears in nft list ruleset.
If you want to see per-IP traffic during an attack on your own network, you can start a 15-day free trial with no credit card and point your router's flow export at it.
Frequently asked questions
What is a good limit_req rate for a WordPress site?
There is no universal number. A common starting point is around 10 requests per second per IP with a burst of 20 for general pages, and 30 requests per minute with a small burst for wp-login.php. Run limit_req_dry_run first and review your logs so you do not block real users.
Does nginx limit_req stop a DDoS attack?
It stops request floods from a limited number of IPs and protects your application workers. It cannot stop a volumetric attack that saturates your uplink, because those packets never reach nginx. For that you need network-level detection and upstream filtering or scrubbing.
Should I disable xmlrpc.php?
If you do not use Jetpack, the WordPress mobile app or other XML-RPC clients, return 403 for it in nginx. If you need it, rate limit it tightly and ban abusive IPs with fail2ban.
Can flow-based detection see HTTP layer 7 floods?
Not directly. NetFlow, IPFIX and sFlow carry addresses, ports, protocols and volume, not URLs or headers. Flow detection catches the bandwidth and packet-rate side of an attack. Low-rate HTTPS floods still need web server controls such as rate limiting, or a WAF.