Nginx rate limit based on location & header of post

denial-of-servicenginx

Nginx has this useful module called ngx_http_limit_req_module
where you can limit requests to the server based on IP or number of requests.

Is it at all possible to rate limit the location that includes the custom header? e.g. I tried this but it fails to start nginx.

location /myservice {
    if ($http_x_custom_header) {
      limit_req zone=one burst=5;
    }
}

The specific error is:

nginx: [emerg] "limit_req" directive is not allowed here in
/etc/nginx/sites-enabled/default

i.e. it doesn't like the limi_req directive inside the if block. It's fine outside the if block.

I may be able to live with different set of limit parameters outside the location though.

Best Answer

You are correct, limit_req can not be used at that level.

The way to get around that is as follows.

error_page 418 = @limitreq;

location /myservice {
    if ($http_x_custom_header) {
      return 418;
    }
}

location @limitreq {
    limit_req zone=one burst=5;
    <rest of config>
    }

This will return 418 if the custom_header is present, which nginx will intercept and send to the custom location block, which will the apply the limit_req