Nginx rate limiting and security headers: limit_req and HSTS
Nginx rate limiting caps how fast one client can send requests with limit_req, and security headers such as HSTS and X-Content-Type-Options tell browsers to apply safer behavior.
- Updated Nov 27, 2026
- Markdown
Rate limit a login route with limit_req, return 429, hide the nginx version and add security headers that survive nesting.
- An nginx server block you can edit with sudo
- HTTPS already working on the site
A public server gets scanned and hammered by bots all day. Two cheap defenses in nginx, served over HTTPS, are a per-client request limit and a set of response headers that make browsers stricter. Both are short in nginx, and both have one trap that this lesson spends time on.
How it works#
limit_req uses a leaky bucket. You define a zone that tracks a key (usually the client IP) and a steady rate such as 10r/s or 30r/m. Requests faster than that go into a burst queue if you allow one, and past the queue they are rejected. limit_conn is different: it caps how many connections one key can hold open at the same time.
Security headers are plain response headers. Each one switches a browser feature on or off for your site: no MIME sniffing, no framing by other sites, less referrer data, HTTPS only. They protect the visitor in the browser, not the server. Rate limits protect the server, and when they work they return a status code of 429 or 503.
Step 1: Define a zone and limit a route#
In the http block (on Ubuntu you can put this in /etc/nginx/conf.d/limits.conf):
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_status 429;Then in the server block:
location = /login {
limit_req zone=login burst=5 nodelay;
proxy_pass http://127.0.0.1:3000;
}$binary_remote_addris the client address in a compact form, so the zone stores more clients per megabyte.zone=login:10mnames the zone and gives it 10 MB of shared memory.rate=5r/mis five requests per minute per client. Pick the number from real traffic, not a guess.burst=5allows five extra requests above the rate before rejecting.nodelayserves the burst at once. Without it nginx spaces the queued requests out, which makes a normal user wait. With it, a client that spends the burst is rejected until slots refill.
If nginx sits behind another proxy or CDN, $remote_addr is that proxy’s address, so every user shares one bucket. Fix the real client address first, for example with the realip module and set_real_ip_from.
Step 2: Limit concurrent connections#
limit_conn_zone $binary_remote_addr zone=perip:10m;
server {
limit_conn perip 20;
limit_conn_status 429;
}This stops one client from holding many slow connections. It protects against simple slow-client abuse but not a large distributed attack, which needs help upstream of your server. For brute force on SSH rather than HTTP see protect SSH with fail2ban.
Step 3: Hide the version and add headers#
server_tokens off;
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;
add_header Content-Security-Policy "frame-ancestors 'self'" always;server_tokens offremoves the version number from theServerheader and error pages. It is a small reduction in information, not a fix for unpatched software.X-Content-Type-Options: nosniffstops browsers guessing a type that differs fromContent-Type.X-Frame-Optionsblocks other sites from framing yours. The modern replacement is the CSPframe-ancestorsdirective, and sending both is fine for older browsers.Referrer-Policylimits what is sent in theRefererheader when users follow a link out.- A full
Content-Security-Policyfor scripts is a bigger project. Start withframe-ancestorsonly.
Step 4: Add HSTS when HTTPS is stable#
add_header Strict-Transport-Security "max-age=31536000" always;HSTS tells the browser to use HTTPS for your domain for that many seconds. Browsers remember it, so a broken certificate later cannot be clicked through. Read HSTS explained and start with a short max-age before a year. Do not add includeSubDomains or preload until every subdomain serves HTTPS.
Step 5: Avoid the inheritance trap#
server {
add_header X-Content-Type-Options "nosniff" always;
location /assets/ {
add_header Cache-Control "public, max-age=31536000"; # drops nosniff here!
}
}Because the location has its own add_header, the server-level line is not applied to /assets/. Fix it by repeating the headers, or put the shared ones in a file and include it in both places:
include /etc/nginx/snippets/security-headers.conf;Check with curl -I on a URL inside every location that sets its own headers.
Check it worked#
sudo nginx -t && sudo systemctl reload nginx
curl -sI https://example.com/ | grep -iE 'server|x-content|x-frame|referrer|strict'
for i in $(seq 1 12); do curl -s -o /dev/null -w '%{http_code}\n' https://example.com/login; doneYou should see the headers on the first command, and after a few quick requests the loop should start printing 429. Rejections are also logged in /var/log/nginx/error.log as limiting requests, excess: .... See nginx from scratch for log locations.
Edge cases and gotchas#
- Shared IPs punish real users. Offices and mobile carriers put many people behind one address, so keep the limit generous on pages and strict on login and password reset.
limit_reqcounts the key, not the user. An attacker using many addresses is not stopped. It slows simple scripts only.- The zone is shared memory. Each state is small, but 10m holds a large number of addresses. A full zone makes nginx reject new keys, so size it with traffic in mind.
- Without
always, error pages lack your headers. nginx addsadd_headeronly on a set of success and redirect codes unless you addalways. X-Frame-Optionscan break embeds you want. If another site must frame yours (a widget), set a CSPframe-ancestorslist instead.- Test before you add
preload. Removing a domain from the browser preload list takes a long time. - Allowlist health checks. Monitoring that hits the same URL every few seconds from one IP can trip a limit. Use
limit_req_zoneon a different location or skip that path.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
nginx: [emerg] "limit_req_zone" directive is not allowed here | Zone defined inside server or location | Move it to the http block |
limiting requests, excess: 5.340 by zone "login" in error.log | The limit is working | Raise burst or rate if real users hit it |
Clients get 503 Service Temporarily Unavailable on limits | Default limit_req_status | Set limit_req_status 429; |
| Header missing in one location only | Child add_header dropped the parent ones | Repeat the headers or include a snippet |
| Header missing on 404 or 500 pages | always not set | Add always |
| Everyone is limited together | $remote_addr is the proxy’s address | Use realip with set_real_ip_from |
nginx: [emerg] zero size shared memory zone "login" | Zone size is zero or missing | Write zone=login:10m |
| Site works in curl but is blocked in a frame | X-Frame-Options or frame-ancestors too strict | Allow the embedding origin in CSP |
Quick reference#
# http block
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_status 429;
server_tokens off;
# server block
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "frame-ancestors 'self'" always;
location = /login {
limit_req zone=login burst=5 nodelay;
}Related lessons#
- HSTS explained: the header that forces HTTPS in browsers.
- Gzip and caching headers: another add_header user, with the same inheritance rule.
- Set up a firewall with ufw: block traffic before it reaches nginx.
- Protect SSH with fail2ban: the same idea for logins over SSH.
- Deploy an Express app with Docker on a VPS: an app that needs a login limit.
Next#
Real-time apps need extra proxy settings, so continue with websockets through a proxy.
Check what you learned
Frequently asked questions
How do I rate limit requests in nginx?
Define a zone with limit_req_zone in the http block, then apply it with limit_req zone=name burst=N in a server or location block. Set limit_req_status 429 so clients get a clear error.
What does burst do in limit_req?
Burst is a queue of extra requests allowed above the steady rate. Without nodelay, queued requests are spaced out. With nodelay, they are served at once and the slots refill at the set rate.
Why do my security headers disappear in some locations?
add_header is inherited from the parent level only when the current level has no add_header of its own. One add_header in a location removes all the inherited ones, so repeat them or use an include file.
How do I hide the nginx version?
Set server_tokens off; in the http block. The Server header then says nginx without a version, and error pages drop the number too.
Sources
Keep going: guides and tutorials
- Self-Hosted Static Site Hosting: Deploy a Folder With Levelrail Self-hosted static site hosting from a plain folder: one deploy command, _redirects, _headers and a custom 404 honored, plus a one command rollback.
- Deploy Next.js on a VPS With Docker, Git Push and HTTPS Deploy a Next.js app to your own VPS with Docker, a health check, HTTPS and rollback. Includes the NEXT_PUBLIC build trap that leaves variables empty.