limit_conn_zone $binary_remote_addr zone=addr:10m; server { location / { limit_conn addr 5; proxy_pass http://backend; } }
The limit_conn directive limits the number of simultaneous connections per defined key (here, per IP address). When the limit is exceeded, nginx rejects the extra connections with a 503 error by default.
The variable $cookie_SESSIONID extracts the value of the cookie named SESSIONID. Using it as the key in limit_conn_zone limits connections per user session.
The limit_conn directive must be placed inside a location, server, or http block. However, to limit connections per location, it should be inside the location block. Placing it only in the server block limits all connections to the server, but sometimes it may not work as expected if location blocks override it.
First, define the zone with limit_conn_zone. Then apply limit_conn in the location block. Reload nginx to apply changes. Finally, test the setup.
Best practice is to limit simultaneous connections per IP using limit_conn_zone and limit_conn, and also limit request rates with limit_req to prevent flooding. This layered approach improves defense against denial-of-service attacks.