Sub topic 15
Hardening and Rate Limiting
This chapter assumes you can install Nginx, edit files under /etc/nginx, and test and reload configuration with nginx -t. It also assumes you know how server and location blocks work and understand basic HTTP and TLS. Hardening reduces what an attacker can learn about your server and limits how much damage one client can do. It does not replace patching, a firewall, or a secure application behind Nginx.
What hardening means for a web server
Hardening has three goals:
- Reveal less. Do not advertise software versions or directory contents.
- Accept less. Reject oversized requests, slow clients, and unneeded HTTP methods.
- Limit abuse. Cap how fast one client can send requests or open connections.
Most of the directives below sit in the http context, so they apply to every site. You can override many of them in a server or location block.
Hide version information
By default Nginx puts its version in the Server header and on its built-in error pages. A version string tells an attacker which known bugs to try. Turn it off in the http context:
http {
server_tokens off;
}After a reload, check the header:
curl -I http://localhostThe header now reads Server: nginx with no version number. This is minor protection. Attackers can still guess your software from its behavior, so treat it as noise reduction, not as a defense.
Limit request rate with limit_req
The limit_req module caps how many requests a client can send over time. You set it up in two steps.
- Declare a shared memory zone with
limit_req_zonein thehttpcontext. - Apply the zone with
limit_reqin aserverorlocationblock.
http {
server_tokens off;
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
server {
listen 80;
location /login {
limit_req zone=perip burst=20 nodelay;
}
}
}The limit_req_zone line has three parts:
$binary_remote_addris the key. Nginx counts requests separately for each distinct key. The binary form of a client address uses less memory than the text form.zone=perip:10mnames the zoneperipand gives it 10 MB of shared memory. One megabyte holds roughly 16,000 IPv4 states, so 10 MB tracks about 160,000 addresses.rate=10r/ssets the sustained limit to 10 requests per second.
How the rate is enforced
Nginx tracks requests with a "leaky bucket" model. A rate of 10 requests per second means Nginx treats one request as allowed every 100 milliseconds. A request that arrives sooner than that is excess.
Without burst, any excess request is rejected at once. That is usually too strict, because browsers send short bursts of requests. The burst parameter sets how many excess requests Nginx will accept beyond the rate.
burst=20alone queues up to 20 excess requests and releases them at the configured rate. Clients see delays.burst=20 nodelayserves the queued requests immediately but still counts the burst slots as used. They free up at the configured rate. Clients see no delay until the burst is exhausted.- Once the burst is full, further requests are rejected.
Choose the rejection status
Rejected requests get status 503 by default. The more accurate status is 429, Too Many Requests. Set it with limit_req_status:
location /login {
limit_req zone=perip burst=20 nodelay;
limit_req_status 429;
}Rejections are written to the error log, at error level by default. You can lower the level with limit_req_log_level warn; to keep the log quieter.
Test the limit
This loop sends 40 quick requests and prints the status code of each:
for i in $(seq 1 40); do
curl -s -o /dev/null -w "%{http_code}\n" http://localhost/login
done | sort | uniq -cWith the configuration above, the first requests return their normal status, and later ones return 429 once the burst of 20 is spent. The exact split depends on how fast your machine sends them.
Limit concurrent connections
limit_req counts requests over time. limit_conn counts connections open at the same moment. It helps against clients that hold many connections open, such as slow download abuse.
http {
limit_conn_zone $binary_remote_addr zone=connperip:10m;
server {
listen 80;
location /downloads/ {
limit_conn connperip 5;
limit_conn_status 429;
}
}
}Each client address may hold at most 5 connections to /downloads/. A browser using HTTP/2 multiplexes many requests over one connection, so a low limit is less likely to hurt normal HTTP/2 users than HTTP/1.1 users.
Pick the right key
The key decides who counts as "one client". A poor key makes the limit either useless or unfair.
| Key | Use it when | Problem |
|---|---|---|
| `$binary_remote_addr` | Nginx faces clients directly | Many users behind one NAT share one limit |
| `$http_x_forwarded_for` | Almost never | The client controls this header and can fake it |
| `$server_name` | You want a global cap per site | One abuser can use up the whole budget |
| A header such as `$http_authorization` | Limiting per API credential | Missing headers produce an empty key |
An empty key is not counted, so requests without the key are not limited at all. Keep that in mind when you key on a header.
If Nginx sits behind a load balancer or CDN, $remote_addr is the address of that proxy, not of the user. Every user then shares one limit. Fix this with the realip module, and trust only addresses you control:
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;Never list addresses you do not control in set_real_ip_from. Anyone in that list can claim any client address.
Restrict request size and timeouts
Large bodies and slow clients tie up workers and memory. Set limits that fit your application:
http {
client_max_body_size 1m;
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
keepalive_timeout 15s;
large_client_header_buffers 4 8k;
}client_max_body_sizerejects larger request bodies with status 413. The default is 1 MB. Raise it only for locations that accept uploads.client_body_timeoutandclient_header_timeoutclose connections from clients that send data too slowly, which blunts slow-request attacks.large_client_header_bufferscaps header size. Oversized headers get status 400 or 414.
Apply a larger limit to one location rather than globally:
location /upload {
client_max_body_size 50m;
}Allow only the methods you need
A static site needs only GET, HEAD, and perhaps OPTIONS. Reject the rest inside a location:
location / {
limit_except GET HEAD {
deny all;
}
try_files $uri $uri/ =404;
}limit_except applies its block to every method not listed. Allowing GET also allows HEAD. The deny all returns status 403 for other methods.
Restrict access by address and block sensitive paths
The allow and deny directives check the client address in order and stop at the first match. Use them for admin areas:
location /admin/ {
allow 192.0.2.0/24;
allow 203.0.113.10;
deny all;
}Block hidden files, such as .git and .env, which often leak source code and secrets when someone deploys a repository into the web root:
location ~ /\.(?!well-known) {
deny all;
}The negative lookahead keeps /.well-known/ reachable. Certificate authorities use that path to validate domain ownership. If you use a regex location, remember from the matching chapter that a regex location can win over a prefix location, so check that your admin and static rules still reach the right handler.
Also keep directory listings off. autoindex is off by default, so only turn it on for a path where listing is intended.
Add security headers and strengthen TLS
Response headers tell browsers to enforce extra protections. Set them in the server block that uses HTTPS:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}Strict-Transport-Security(HSTS) tells browsers to use HTTPS only for this site for the given number of seconds. Start with a short value while you test, because a browser that has stored HSTS cannot fall back to HTTP.X-Content-Type-Options: nosniffstops browsers from guessing a content type different from the one you send.X-Frame-Optionslimits who may embed your pages in a frame.alwaysadds the header on error responses too. Without it, Nginx adds the header only to successful responses.
ssl_protocols TLSv1.2 TLSv1.3 disables the old SSL and TLS 1.0 and 1.1 protocols. The default list in current Nginx releases is already safe, but stating it makes the policy visible and stable across upgrades.
Run with least privilege
Nginx starts a master process as root, because it must bind ports 80 and 443. The worker processes handle requests and should run as an unprivileged user. Check the user directive at the top of nginx.conf:
user www-data;Debian and Ubuntu use www-data. Other distributions often use nginx. Confirm that workers are not root:
ps -o user,pid,cmd -C nginxAlso protect the files:
- Keep private keys readable only by root, for example mode
600or640, with a group for services that need them. - Make web-root files readable by the worker user, but not writable. A compromised worker should not be able to change the site.
- Do not store secrets under the web root.
Defense in depth
Nginx settings are one layer. Combine them with others:
- Open only ports 80 and 443 in the firewall, plus SSH from trusted addresses.
- Keep Nginx updated through the package manager.
- Use a reverse proxy limit such as
limit_reqin front of the application, but also validate input inside the application. - Review logs for repeated 403, 404, 429, and 413 responses, which show probing.
The sequence below shows how a request passes the limits in this chapter.
The order in the diagram is a simplification. Nginx processes requests in phases, and the body-size check happens when it reads the request headers, before the body arrives. The point is that every request passes several independent checks.
Apply changes safely
Always test before you reload, so a typo does not take the site down:
sudo nginx -t && sudo systemctl reload nginxThen verify each control from outside:
curl -Ishows no version and shows your security headers.- The request loop returns 429 after the burst.
- A request to
/.git/configreturns 403. - A
POSTto a read-only location returns 403.
Common mistakes
- Setting
ratevery low andburstto zero, which blocks normal page loads that fetch many files at once. - Applying a strict limit to the whole site when only
/loginor an API path needs it. - Keying on
$remote_addrbehind a proxy withoutrealip, so all users share one bucket. - Adding one
add_headerin alocationand losing the server-level headers. - Enabling HSTS with a long lifetime before HTTPS works for every subdomain you use.
Exercise
Your site sits behind a CDN. After you add limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/s; and limit_req zone=perip burst=10 nodelay;, almost every visitor starts receiving 429 responses during normal use. What is the likely cause, and how do you fix it?
Show answer
Nginx sees the CDN's address as the client address, so all visitors share one rate bucket. Fix it with the realip module: set set_real_ip_from to the CDN's address ranges (only ranges you trust), set real_ip_header to the header the CDN uses, such as X-Forwarded-For, then run nginx -t and reload. The limit then counts each real visitor separately.
Exercise
A location sets add_header Cache-Control "no-store";. The server block above it sets Strict-Transport-Security. A test shows the HSTS header is missing on responses from that location. Why, and what are two ways to fix it?
Show answer
A block that defines any add_header does not inherit add_header directives from outer levels. To fix it, either repeat the HSTS header inside that location, or move the shared headers into an included file and include that file in the server block and in the location.