Protection

7 min readUpdated

nginx DDoS protection: a configuration for small floods, and its limits

Quick answer

nginx can blunt small application-layer floods on its own. limit_req caps the request rate per client address, limit_conn caps concurrent requests, short timeouts close slow clients, size limits refuse oversized requests and a cache keeps serving when the backend struggles. It cannot stop an attack that fills the server's network link or exhausts the kernel before nginx reads a request; that has to be filtered upstream.

01Can nginx protect a site against DDoS attacks?

Against small floods at the HTTP layer, yes; against anything that fills the network link, no. nginx acts only on requests it has received, so it can refuse, delay or cache its way through a flood from a limited number of addresses, but every packet has already crossed the server's uplink by then. The table sorts common attacks by how much nginx on the origin can do.

Attacknginx on the originWhy
HTTP flood from a few hundred addressesHelpslimit_req and limit_conn refuse the excess per address; see HTTP floods and, for burst and nodelay in detail, nginx rate limiting
HTTP flood from tens of thousands of addressesPartlyEach address can stay under a per-address limit; caching and per-route limits reduce the cost
Slowloris and slow request bodiesHelpsShort header and body timeouts close the connections; see Slowloris
Login brute forceHelpsA strict per-address zone on the login route
TLS handshake floodPartlyThe handshake is complete before limit_req sees a request; see SSL floods
SYN floodNoHandled by the kernel, below nginx; see SYN floods
UDP or amplification floodNoThe traffic never reaches nginx, but it fills the link; see amplification attacks

02How to configure limit_req and limit_conn in nginx

limit_req counts requests per key using the leaky-bucket method; limit_conn counts concurrent requests per key. Both keep their state in a shared memory zone declared at http level and applied at server or location level. The key here is $binary_remote_addr, which is the visitor only if nginx real IP is configured behind a proxy. Without it, every visitor shares the proxy's bucket.

rate=10r/s with burst=20 nodelay lets a client send 21 requests at once, after which one slot frees every 100 milliseconds. On one keep-alive connection, 40 back-to-back requests produced 21 responses with status 200 and 19 with 429; after a one-second pause, 10 more succeeded. Without nodelay, the 20 extra requests would have been queued and released one every 100 milliseconds instead. The login zone let 6 requests through and refused the rest.

limit_conn counts only connections with a request in progress whose header has been read completely, so it ignores idle keep-alive connections and a Slowloris client still sending its header; under HTTP/2 and HTTP/3 each concurrent request counts. Twenty-five parallel slow downloads from one address gave 20 successes and 5 refusals. Both modules answer 503 by default; 429 is the accurate status, as 429 Too Many Requests explains.

Rate and connection limits (passes nginx -t, nginx 1.22.1)
# http {} level: 10 MB holds about 80,000 limit_req or 160,000 limit_conn entries
limit_req_zone  $binary_remote_addr zone=perip:10m rate=10r/s;
limit_req_zone  $binary_remote_addr zone=login:10m rate=10r/m;
limit_conn_zone $binary_remote_addr zone=peraddr:10m;
limit_req_status  429;
limit_conn_status 429;

# server {} level
limit_req  zone=perip burst=20 nodelay;
limit_conn peraddr 20;

location = /login {
    # limit_req is inherited only when a level has none of its own,
    # so repeat the general limit next to the stricter one.
    limit_req zone=perip burst=20 nodelay;
    limit_req zone=login burst=5 nodelay;
    proxy_pass http://127.0.0.1:8080;
}

03Which nginx timeouts and size limits matter in a flood?

nginx's defaults are generous: 60 seconds to send the header or each chunk of the body, and 75 seconds for an idle keep-alive connection. A flood of slow clients holds a connection for every one of those seconds. Shorter values free them sooner, at the cost of cutting off genuinely slow clients, so stay well above what real users on poor mobile connections need.

DirectiveDefaultValue hereEffect (times measured in the test)
client_header_timeout60s10sHalf a request line, then silence: reset after 10.0 s, logged as 408
client_body_timeout60s10sApplies between two reads, not to the whole upload; a stalled body was reset after 10.0 s
send_timeout60s10sCloses a client that stops reading the response
keepalive_timeout75s15sAn idle keep-alive connection was closed after 15.0 s
reset_timedout_connectionoffonSends a TCP reset and frees the socket's memory at once
client_max_body_size1m1mA 2 MB POST got 413 before its body was read
large_client_header_buffers4 8k4 8kA 9,000-byte header line got 400 Request Header Or Cookie Too Large
Timeouts and size limits, http {} level
client_header_timeout 10s;
client_body_timeout   10s;
send_timeout          10s;
keepalive_timeout     15s;
reset_timedout_connection on;

client_max_body_size        1m;   # raise it only in upload locations
large_client_header_buffers 4 8k;

04How many connections can nginx hold during an attack?

Each worker process holds up to worker_connections connections, and that number includes connections to upstream servers, so a proxied request uses two. Every connection is also an open file, and worker_rlimit_nofile raises that limit for the workers without restarting the master process.

On a six-core server this gives 6 × 16,384 = 98,304 connection slots, or about 49,000 proxied clients at once. Each worker needs one descriptor per connection plus a few for logs and cache files, which 65,535 covers. Zone sizes need the same arithmetic: on 64-bit systems a limit_req state takes 128 bytes, so 10 MB holds about 80,000 addresses, and a limit_conn state takes 64 bytes, so 10 MB holds about 160,000. A full limit_req zone evicts its least recently used entry, but a full limit_conn zone returns an error to every further request, so size that zone for the largest number of addresses you expect.

The kernel's accept queue sits in front of all this. nginx requests a listen backlog of 511 on Linux unless backlog= is set, and the kernel silently caps it at net.core.somaxconn, which defaults to 4096 since Linux 5.4.

Worker limits, main context
worker_processes auto;          # one worker per CPU core
worker_rlimit_nofile 65535;
events {
    worker_connections 16384;
}

05How does caching keep a site up during an HTTP flood?

A request served from cache costs nginx little and the application nothing. Even ten seconds of caching for anonymous pages turns thousands of identical requests into one upstream request every ten seconds, and proxy_cache_use_stale keeps serving the last good copy when the backend errors or times out.

In the test, the second request was a HIT, and after the backend was stopped and the entry had expired, nginx still answered 200 with STALE. proxy_cache_lock lets only one request at a time fill a missing entry, and the others wait up to proxy_cache_lock_timeout, 5 seconds by default, holding their connections while they wait. Responses that set cookies are not cached, and requests with an Authorization header or a session cookie, called session here, bypass the cache, so personal pages are never shared between visitors.

A short cache that serves stale copies when the backend fails
# http {} level
proxy_cache_path /var/cache/nginx/micro levels=1:2 keys_zone=micro:10m
                 max_size=1g inactive=10m use_temp_path=off;

# inside location / { ... }
proxy_cache micro;
proxy_cache_valid 200 301 302 10s;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
proxy_cache_bypass $http_authorization $cookie_session;
proxy_no_cache     $http_authorization $cookie_session;
# an add_header here stops server-level add_header lines being inherited
add_header X-Cache-Status $upstream_cache_status always;

06What does a flood look like in the nginx logs?

Refused requests are logged at error level by default, one line each, which adds up quickly during a flood; limit_req_log_level and limit_conn_log_level lower that level. The first three lines below came from the tests above, followed by two ways to read the access log in the default combined format.

Before enforcing a new limit, run it with limit_req_dry_run on, available since nginx 1.17.1. Nothing is refused, but the zone still counts excess requests and $limit_req_status reports REJECTED_DRY_RUN, which can be written to the access log to see who would have been turned away.

Error log lines from the tests (shortened), and awk one-liners for the access log
limiting requests, excess: 20.930 by zone "perip", client: 127.0.0.5, server: example.com, request: "GET /index.html HTTP/1.1"
limiting connections by zone "peraddr", client: 127.0.0.7, server: example.com, request: "GET /big.bin HTTP/1.1"
client intended to send too large body: 2097152 bytes, client: 127.0.0.8, server: example.com, request: "POST /upload HTTP/1.1"

# top sources of 429 responses
awk '$9 == 429 {print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# 429 responses per minute
awk '$9 == 429 {print substr($4, 2, 17)}' /var/log/nginx/access.log | sort | uniq -c

07What can't nginx stop?

Everything above happens after a packet has crossed the server's network link, been accepted by the kernel and, for HTTPS, completed a TLS handshake. An attack that saturates the link has won before nginx runs. Cloudflare reported 805 network-layer attacks above 1 Tbps in the second quarter of 2026 alone, and a single 1 Tbps flood is a thousand times the capacity of a 1 Gbit/s server port.

That is the line between hardening and DDoS protection. A firewall on the same server hits the same ceiling, as can a firewall stop a DDoS attack works through. The traffic has to be filtered upstream, on a network with more capacity than the attack, which is what DDoS protection services do.

  • Volumetric floods over UDP or amplification fill the uplink, and no nginx setting changes that.
  • Per-address limits assume few addresses: 50,000 bots sending 5 requests per second each make 250,000 requests per second, while every one of them stays under a 10 r/s limit.
  • TLS handshakes are paid for before limit_req sees a request, so a handshake flood costs CPU even when every request is refused.
  • Protocol flaws need patches, not limits, as HTTP/2 Rapid Reset showed; an old distribution build is worth checking against the nginx 1.18.0 vulnerability triage.
  • A server behind a proxy without real-IP restoration limits the proxy, not the attacker.

Questions

Frequently asked questions

01What is a good limit_req rate for nginx?
There is no universal number. Measure first: count requests per address per second for real visitors in the access log, or run the zone in dry-run mode, then set the rate a little above what legitimate clients reach and use burst for page loads that fetch many assets at once. Login, search and API routes usually deserve their own stricter zones.
02What is the difference between burst and nodelay in limit_req?
burst sets how many requests above the rate nginx accepts instead of refusing. Without nodelay those extra requests are queued and released at the configured rate, which makes a burst slow. With nodelay they are processed at once, while their slots still free up at the configured rate, so the long-run limit stays the same and only the delay disappears. The separate guide to nginx rate limiting measures the difference with 20 simultaneous requests.
03Should nginx rate limiting return 429 or 503?
429. Both limit_req and limit_conn return 503 by default, which tells clients and monitoring that the server is unavailable and can be mistaken for an outage. Setting limit_req_status 429 and limit_conn_status 429 reports the real reason, Too Many Requests, so well-behaved clients can slow down instead of retrying as if the server were broken.
04Does limit_conn stop a Slowloris attack?
Not on its own. limit_conn counts only connections that have a request in progress whose header has been read completely, and a Slowloris client never finishes its header. Short client_header_timeout and client_body_timeout values are what close those connections, ideally with reset_timedout_connection on, so the sockets are freed at once instead of lingering.
05Can nginx stop a DDoS attack by itself?
Only a small one at the application layer. Rate limits, timeouts and caching can absorb a flood from a limited number of addresses. Nothing in nginx helps when the attack fills the server's network link or overwhelms the kernel first, because that traffic is lost before nginx reads it. Those attacks have to be filtered upstream, before they reach the server.

Sources

Sources and verification

Checked on 13 November 2026 on Debian 12: the nginx configuration in “How to configure limit_req and limit_conn in nginx” passes nginx -t (nginx 1.22.1); the nginx configuration in “Which nginx timeouts and size limits matter in a flood?” passes nginx -t (nginx 1.22.1). Other configuration, commands, log lines and output on this page are examples: adapt them to your system and check them before use.

  1. 01Module ngx_http_limit_req_module · nginx.org
  2. 02Module ngx_http_limit_conn_module · nginx.org
  3. 03Module ngx_http_core_module (timeouts, buffers, listen backlog) · nginx.org
  4. 04Core functionality (worker_connections, worker_rlimit_nofile) · nginx.org
  5. 05Module ngx_http_proxy_module (proxy_cache) · nginx.org
  6. 06Rate Limiting with NGINX · NGINX blog
  7. 07Mitigating DDoS Attacks with NGINX and NGINX Plus · NGINX blog
  8. 08Cloudflare DDoS Threat Report H1 2026 · Cloudflare
  9. 09listen(2) Linux manual page · man7.org

Last updated