Search code examples
kubernetesluanginx-ingress

How to use Lua script with ingress-nginx


I would like to use a Lua script with ingress-nginx to block traffic to the specific path. I created the below config, but it doesn't work as expected.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
    nginx.ingress.kubernetes.io/server-snippet: |
      location /app-2 {
            rewrite_by_lua_block {
              ngx.status = 403;
              ngx.exit(ngx.HTTP_FORBIDDEN);
        }
      }
spec:
  rules:
    - http:
        paths:
          - path: /app-1
            pathType: Prefix
            backend:
              service:
                name: app-1
                port:
                  number: 80
          - path: /app-2
            pathType: Prefix
            backend:
              service:
                name: app-2
                port:
                  number: 80
              
~ curl http://A.B.C.D/app-2
<html><body><h1>It works!</h1></body></html>

Solution

  • So this creates a location context in your nginx.conf (under a server context):

    - path: /app-2
      pathType: Prefix
      backend:
        service:
          name: app-2
          port:
            number: 80
    

    and this also creates a location context with the same name:

    location /app-2 {
          rewrite_by_lua_block {
            ngx.status = 403;
            ngx.exit(ngx.HTTP_FORBIDDEN);
      }
    }
    

    It's likely that this one is defined above the other one so it's overriding it.

    You can check with this:

    kubectl cp <nginx-ingress-controller-pod> -c nginx nginx.conf nginx.conf
    cat nginx.conf