Chapter 8 · Lesson 6 of 8
Web servers and proxies

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.

By the end you will

Rate limit a login route with limit_req, return 429, hide the nginx version and add security headers that survive nesting.

Time
25 min
Level
Intermediate
Check
4 questions
You need
  • 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):

nginx
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_status 429;

Then in the server block:

nginx
location = /login {
    limit_req zone=login burst=5 nodelay;
    proxy_pass http://127.0.0.1:3000;
}
  • $binary_remote_addr is the client address in a compact form, so the zone stores more clients per megabyte.
  • zone=login:10m names the zone and gives it 10 MB of shared memory.
  • rate=5r/m is five requests per minute per client. Pick the number from real traffic, not a guess.
  • burst=5 allows five extra requests above the rate before rejecting.
  • nodelay serves 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#

nginx
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#

nginx
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 off removes the version number from the Server header and error pages. It is a small reduction in information, not a fix for unpatched software.
  • X-Content-Type-Options: nosniff stops browsers guessing a type that differs from Content-Type.
  • X-Frame-Options blocks other sites from framing yours. The modern replacement is the CSP frame-ancestors directive, and sending both is fine for older browsers.
  • Referrer-Policy limits what is sent in the Referer header when users follow a link out.
  • A full Content-Security-Policy for scripts is a bigger project. Start with frame-ancestors only.

Step 4: Add HSTS when HTTPS is stable#

nginx
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#

nginx
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:

nginx
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#

bash
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; done

You 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_req counts 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 adds add_header only on a set of success and redirect codes unless you add always.
  • X-Frame-Options can break embeds you want. If another site must frame yours (a widget), set a CSP frame-ancestors list 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_zone on a different location or skip that path.

Troubleshooting#

SymptomLikely causeFix
nginx: [emerg] "limit_req_zone" directive is not allowed hereZone defined inside server or locationMove it to the http block
limiting requests, excess: 5.340 by zone "login" in error.logThe limit is workingRaise burst or rate if real users hit it
Clients get 503 Service Temporarily Unavailable on limitsDefault limit_req_statusSet limit_req_status 429;
Header missing in one location onlyChild add_header dropped the parent onesRepeat the headers or include a snippet
Header missing on 404 or 500 pagesalways not setAdd always
Everyone is limited together$remote_addr is the proxy’s addressUse realip with set_real_ip_from
nginx: [emerg] zero size shared memory zone "login"Zone size is zero or missingWrite zone=login:10m
Site works in curl but is blocked in a frameX-Frame-Options or frame-ancestors too strictAllow the embedding origin in CSP

Quick reference#

nginx
# 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;
}

Next#

Real-time apps need extra proxy settings, so continue with websockets through a proxy.

Check what you learned4 questions
1Where must limit_req_zone be defined?
2A location sets one add_header line of its own. What happens to the add_header lines in its parent server block?
3What does the always parameter on add_header do?
4Which line makes rate-limited clients receive 429 instead of 503?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios