Search code examples
nginxkuberneteskubernetes-ingressnginx-ingressrate-limiting

How to add limit_req zone for a particular location in nginx ingress


I have an ingress something like below

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: staging-ingress-rules-login
  annotations:
    kubernetes.io/ingress.class: 'nginx'
    nginx.ingress.kubernetes.io/proxy-body-size: '0'
spec:
  rules:
  - host: staging.mysite.com
    http:
      paths:
      - path: /
        backend:
          serviceName: login
          servicePort: 80
      - path: /login/info
        backend:
          serviceName: login
          servicePort: 80

and the nginx.conf for this is something like this

server { 
 location / {
   ---------
   ---------
}

location /login/info {
  ---------
  -------
}

} 

I would like to add the rate limit for location /login.info, i tried location-snippet but it is creating nested location inside /login/info and the result for this api is giving 404, any way to do this ?


Solution

  • This is a community wiki answer, feel free to edit and expand it.

    As we are lacking some details regarding your configuration, I will explain how you can deal with this in general.

    You can use the below annotation in order to add a custom location block:

    nginx.ingress.kubernetes.io/configuration-snippet: |
      limit_req zone=authentication_ratelimit nodelay;
    

    And than use a map, for example:

    http-snippets: |
      map $uri $with_limit_req {
        default 0;
        "~*^/authenticate$" 1;
      }
      map $with_limit_req $auth_limit_req_key {
        default '';
        '1'     $binary_remote_addr; # the limit key
      }
      limit_req_zone $auth_limit_req_key zone=authentication_ratelimit:10m rate=1r/s;
    

    Notice that:

    Syntax:   limit_req_zone key zone=name:size rate=rate [sync];
    Default:  —
    Context:  http
    

    Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state stores the current number of excessive requests. The key can contain text, variables, and their combination. Requests with an empty key value are not accounted.