Search code examples
nginxkubernetesnginx-ingress

Remove prefix after match before forwarding request to service


I have this base url api.example.com

So, ingress-nginx will get the request for api.example.com and it should do follow things.

Forward api.example.com/customer to customer-srv

It doesn't work, it forwards whole mtach to customer-srv i.e. /customer/requested_url

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  rules:
    - host: api.example.in
      http:
        paths:
          - path: /customer/?(.*)
            pathType: Prefix
            backend:
              service:
                name: customer-srv
                port:
                  number: 3000

I tried using rewrite annotation but that doesn't work either however this worked but this is not I want to achieve.

    paths:
      - path: /?(.*)
        pathType: Prefix
        backend:
          service:
            name: customer-srv
            port:
              number: 3000

For example,

api.example.com/customer should go to http://localhost:3000 not http://localhost:3000/customer


Solution

  • Here is the yaml I used:

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      name: ingress-service
      annotations:
        kubernetes.io/ingress.class: nginx
        nginx.ingress.kubernetes.io/rewrite-target: /$1
    spec:
      rules:
        - host: api.example.in
          http:
            paths:
              - path: /customer/?(.*)
                pathType: Prefix
                backend:
                  service:
                    name: customer-srv
                    port:
                      number: 3000
    

    For test purpouses I created an echo server:

    kubectl run --image mendhak/http-https-echo customer
    

    And then a service:

    kubectl expose po customer --name customer-srv --port 3000 --target-port 80
    

    I checked igress ip:

    $ kubectl get ingress
    NAME                  CLASS    HOSTS               ADDRESS          PORTS   AGE
    ingress-service       <none>   api.example.in      192.168.39.254   80      3m43s
    

    And I did a curl to check it:

    curl 192.168.39.254/customer/asd -H "Host: api.example.in"           
    {
      "path": "/asd",
      "headers": {
        "host": "api.example.in",
    
    ...
    }
    

    Notice that the echo server echoed back a path that it received, and sice it received a path that got rewritten from /customer/asd to /asd it shows this exectly path (/asd).

    So as you see this does work.