brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: nginx limit_conn caps simultaneous connections per IP address

Nginx
~/tips/tip-nginx-limit-conn-per-ip

limit_conn addr 1;

Limits how many connections one IP address may keep open at once.

limit_req slows down how fast one client may ask. limit_conn is the other half: it caps how many connections one client may hold open at the same time, which suits big downloads.

You need two pieces. limit_conn_zone goes in the http block and defines a shared memory zone that keeps a state per key, including the current number of connections. limit_conn then picks that zone and a maximum, in http, server or location. The example from the nginx documentation allows one connection per IP address at a time on a download location:

http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    server {
        location /download/ {
            limit_conn addr 1;
        }
    }
}

The docs use $binary_remote_addr and not $remote_addr on purpose. The binary form is always 4 bytes for IPv4 and 16 for IPv6, while the text form varies between 7 and 15 bytes, so the zone holds more clients. One megabyte stores about 32 thousand 32-byte states or about 16 thousand 64-byte states, so the 10 MB in the example is generous for a home server.

Clients over the limit get an error. The default status is 503, and limit_conn_status changes it, for example to 429 if you prefer that one. Rejections are logged at the error level by default, which limit_conn_log_level can change.

limit_conn_status 429;
limit_conn_log_level warn;

There are two caveats. First, the key is the address nginx sees. If nginx sits behind another proxy, every visitor may share that proxy’s address and one shared counter, so sort out the real client address first. The same goes for several people behind one home or office connection: a limit of 1 would block the second person. Second, the zone has a fixed size; the docs say that when its storage is exhausted, nginx returns the error to all further requests. Leave some room.

Check the file with nginx -t before you reload.

Further reading: ngx_http_limit_conn_module

Going deeper: ๐Ÿ›œ Guide: AdGuard Home + Tailscale (Secure Split-Horizon DNS)

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link