Nginx : How to set 'limit_conn' and 'limit_req'?

Solution

Merge /etc/nginx/sites-enabled/service.conf into /etc/nginx/nginx.conf. In other words, remove service.conf file and paste server block at nginx.conf file's http block. Here is code.

/etc/nginx/nginx.conf

http {

    ..

    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=2r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

    ..

    server {

        ..

        location / {
            limit_req zone=req_limit_per_ip burst=5 nodelay;
            limit_conn conn_limit_per_ip 30;
        }

        ..
    }
}

Meaning of variables and Test

  1. limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=2r/s + limit_req zone=req_limit_per_ip burst=5 nodelay

    • Set shared memory as 10MB
    • Limit requests per IP as following
    • Set maximum requests as rate * burst in burst seconds
    • For example, maximum value is 10(=2*5) requests in 5 seconds in this case
    • With nodelay option : Nginx would return 503 response and not handle excessive requests
    • Without nodelay option : Nginx would wait (no 503 response) and handle excessive requests with some delay
  2. limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m + limit_conn conn_limit_per_ip 30

    • Set shared memory as 10MB
    • Limit connections per IP as 30 in this case
    • Note that normal browser makes 2~8 connections and SPDY protocol split each connections
    • Nginx would return 503 response if connection exceeds this value

The directives limit_req_zone and limit_conn_zone just need precede the corresponding directives included in /etc/nginx/sites-enabled/service.conf.

So in Case 1 just need to change /etc/nginx/nginx.conf to:

http {
    ...
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;
    ...
    include /etc/nginx/sites-enabled/*;
    ...
}

See:

  1. http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html
  2. http://nginx.org/en/docs/http/ngx_http_limit_req_module.html