3

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

Community
  • 1
  • 1
zono
  • 8,366
  • 21
  • 75
  • 113

2 Answers2

2

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;
}
zono
  • 8,366
  • 21
  • 75
  • 113
0

For setting up a rate limit in Nginx base on HTTP headers you can use $http_example_header variable. In your case, you can have something like this:

limit_req_zone $http_x_api_key zone=example_zone:10m rate=10r/s;

server {
     listen 80;

     location /xxx {
          limit_req zone=example_zone;
          limit_req_status 429;
     }
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 01 '23 at 02:38