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

URL: https://levelrail.com/learn/web-servers/rate-limiting-and-security-headers/
Updated: 2026-11-27

A public server gets scanned and hammered by bots all day. Two cheap defenses in [nginx](https://levelrail.com/learn/glossary/#nginx)), served over [HTTPS](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/glossary/#http-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](https://levelrail.com/learn/server-basics/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](https://levelrail.com/learn/domains-https/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](https://levelrail.com/learn/web-servers/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

| 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

```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;
}
```

## Related lessons

- [HSTS explained](https://levelrail.com/learn/domains-https/hsts-explained/)): the header that forces HTTPS in browsers.
- [Gzip and caching headers](https://levelrail.com/learn/web-servers/gzip-and-caching-headers/)): another add_header user, with the same inheritance rule.
- [Set up a firewall with ufw](https://levelrail.com/learn/server-basics/set-up-a-firewall-with-ufw/)): block traffic before it reaches nginx.
- [Protect SSH with fail2ban](https://levelrail.com/learn/server-basics/protect-ssh-with-fail2ban/)): the same idea for logins over SSH.
- [Deploy an Express app with Docker on a VPS](https://levelrail.com/blog/deploy-express-app-docker-vps/)): an app that needs a login limit.

## Next

Real-time apps need extra proxy settings, so continue with [websockets through a proxy](https://levelrail.com/learn/web-servers/websockets-through-a-proxy/)).

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

- [Nginx docs, ngx_http_limit_req_module](https://nginx.org/en/docs/http/ngx_http_limit_req_module.html)
- [Nginx docs, ngx_http_limit_conn_module](https://nginx.org/en/docs/http/ngx_http_limit_conn_module.html)
- [Nginx docs, ngx_http_headers_module](https://nginx.org/en/docs/http/ngx_http_headers_module.html)
