How can you limit the number of simultaneous connections in Nginx? nginx

How can you limit the number of simultaneous connections in Nginx?


Nov. 12, 2023

How can you limit the number of simultaneous connections in Nginx?

Nginx is a powerful web server that can handle a large number of simultaneous connections. However, in certain cases, it may be necessary to limit the number of connections to ensure smooth performance and prevent overload. This can be done using Nginx's built-in features and directives. Here's how you can do it:

1. Use the 'worker_connections' directive

The 'worker_connections' directive is used to define the maximum number of simultaneous connections that can be handled by each worker process of Nginx. By default, this value is set to 512. To limit the number of connections, you can simply set a lower value for this directive in the Nginx configuration file. For example:

worker_connections 100;

This will limit the number of simultaneous connections per worker process to 100.

2. Use the 'limit_conn_zone' and 'limit_conn' directives

The 'limit_conn_zone' and 'limit_conn' directives are used to limit the number of connections from a specific IP address or a defined group of IP addresses. These directives require the 'http_limit_conn_module' to be enabled in Nginx.

First, you need to define a shared memory zone using the 'limit_conn_zone' directive. For example:

limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

This creates a shared memory zone 'conn_limit_per_ip' with a size of 10 megabytes, and it uses the client's IP address as the key.

Then, you can use the 'limit_conn' directive within a specific location block to limit the number of connections. For example:

location / { limit_conn conn_limit_per_ip 10; }

This will limit the number of connections to 10 per IP address in the specified location.

3. Use the 'limit_req_zone' and 'limit_req' directives

If you want to limit the number of requests per second rather than the number of connections, you can use the 'limit_req_zone' and 'limit_req' directives. These directives require the 'http_limit_req_module' to be enabled in Nginx.

Similar to 'limit_conn_zone', you need to define a shared memory zone using the 'limit_req_zone' directive. For example:

limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=1r/s;

This defines a shared memory zone 'req_limit_per_ip' with a size of 10 megabytes and a rate of 1 request per second per IP address.

Then, you can use the 'limit_req' directive within a specific location block to limit the number of requests. For example:

location / { limit_req zone=req_limit_per_ip burst=5; }

This will limit the number of requests to 1 per second per IP address with a burst of up to 5 requests in the specified location.

By using these directives, you can efficiently limit the number of simultaneous connections in Nginx to ensure optimal performance and prevent overload.

nginx