Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx: limit_req based on http header

Tags:

nginx

We provide some JSON Web APIs. Users can create API key on our web page then use the key as HTTP header attribute. However, we will allow to access without the key for trial use. In this case, how can we set up nginx configuration?

sample request

curl  -H 'x-api-key:xxxx' https://api.xxx.com/xxx

We need to set up both (1) and (2)

(1) Without 'x-api-key' http header -> limit_req setting (e.g 10 request per sec)

(2) With 'x-api-key' http header -> no limitation.

Update 1

This is almost same question.

Rate limit in nginx based on http header

like image 505
zono Avatar asked Apr 30 '26 19:04

zono


1 Answers

I found this way and it worked but still not sure whether this setting is ideal or not (looks weird..). I would be grateful you can give me any suggestions.

map $http_x_api_key $limit {
    ""     $binary_remote_addr;
    default     ""; 
}

limit_req_zone $limit zone=limit_req_by_ip:10m rate=1r/s;
limit_req_log_level error;
limit_req_status 503;

location / {
    limit_req zone=limit_req_by_ip burst=10 nodelay;
}
like image 162
zono Avatar answered May 04 '26 10:05

zono