0
0
NginxHow-ToBeginner · 3 min read

How to Use limit_conn in Nginx to Control Connections

Use the limit_conn_zone directive to define a shared memory zone for tracking connections, then apply limit_conn inside a server or location block to limit simultaneous connections per key, such as per IP address. This helps prevent overload by restricting how many connections a client can open at once.
📐

Syntax

The limit_conn_zone directive defines a shared memory zone and the key to track connections (e.g., $binary_remote_addr for client IP). The limit_conn directive sets the maximum number of simultaneous connections allowed per key in a context like http, server, or location.

  • limit_conn_zone key zone=name:size; - defines tracking zone
  • limit_conn zone_name number; - limits connections per key
nginx
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    listen 80;
    limit_conn addr 10;
    location / {
        # your config
    }
}
💻

Example

This example limits each client IP to 5 simultaneous connections. It defines a 10MB shared memory zone named addr to track connections by IP, then applies the limit inside the server block.

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

    server {
        listen 80;

        limit_conn addr 5;

        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}
Output
When a client opens more than 5 simultaneous connections, Nginx returns a 503 Service Unavailable error for the extra connections.
⚠️

Common Pitfalls

  • Not defining limit_conn_zone before using limit_conn causes configuration errors.
  • Using an insufficient zone size can cause inaccurate tracking; 10MB is usually enough for many clients.
  • Applying limit_conn in the wrong context (like outside http or server) will not work.
  • Confusing limit_conn with limit_req which limits request rate, not connections.
nginx
http {
    # Wrong: missing limit_conn_zone

    server {
        listen 80;
        limit_conn addr 5;  # Error: addr zone not defined
    }
}

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

    server {
        listen 80;
        limit_conn addr 5;
    }
}
📊

Quick Reference

DirectivePurposeContextExample
limit_conn_zoneDefines shared memory zone and key for tracking connectionshttplimit_conn_zone $binary_remote_addr zone=addr:10m;
limit_connLimits number of simultaneous connections per keyhttp, server, locationlimit_conn addr 5;

Key Takeaways

Always define limit_conn_zone before using limit_conn to track connections by key.
Use $binary_remote_addr as the key to limit connections per client IP efficiently.
Set an appropriate zone size (e.g., 10m) to store connection states reliably.
Apply limit_conn inside server or location blocks to enforce connection limits.
Exceeding the limit returns a 503 error to clients opening too many connections.