Kubernetes Ingress Nginx - path forwarding does not work

Kubernetes Ingress Nginx - path forwarding does not work

Background: Kubernete Ingress serves as entry point to your services, you can define paths, which can be then forwarded to individual services

Problem: When migrating to latest version of Kubernetes, when attempting to access some path: e.g. https://my-ingress.com/test1/js/my.js file, it always returned content of /test1/index.html instead of the .js file

Original kubernetes ingress resource config file:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-resource
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - http:
      paths:
      - path: /test1
        backend:
          serviceName: nginx-svc
          servicePort: 8080

After few hours of struggle, reading the original docs helped me (yes, RTFM): https://github.com/kubernetes/ingress-nginx/tree/master/docs/examples/rewrite

attention Starting in Version 0.22.0, ingress definitions using the annotation nginx.ingress.kubernetes.io/rewrite-target are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a capture group.

note Captured groups are saved in numbered placeholders, chronologically, in the form $1, $2 ... $n. These placeholders can be used as parameters in the rewrite-target annotation.

That means, that you need to add:

  nginx.ingress.kubernetes.io/rewrite-target: /$1

And change path to contain capture group regex: (.*)

      - path: /test1/(.*)

Now, when attempting to access: https://my-ingress.com/test1/js/my.js the .js file is successfully returned by ingress.

Hope this helps.

Complete file:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-resource
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
  - http:
      paths:
      - path: /test1/(.*)
        backend:
          serviceName: nginx-svc
          servicePort: 8080