Kubernetes nginx ingress rewrite issue

10/16/2019
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
    namespace: default
    name: my-ingress
    annotations:
       kubernetes.io/ingress.class: nginx
       nginx.ingress.kubernetes.io/rewrite-target: $2
spec:
  rules:
    - host: hostname.com
      http:
        paths:
          - path: /
            backend:
              serviceName: frontend
              servicePort: 80
          - path: /api/v1(/|$)(.*)
            backend:
              serviceName: backend
              servicePort: 80

What I am trying to accomplish here is:

hostname.com/api/v1/anyurl should become hostname.com/anyurl when it goes to the backend. hostname.com/anyurl should remain hostname.com/anyurl and go to the frontend.

The /api/v1 rewrite seems to work, but any urls going to the frontend gets rewrited to /. What I need is the rewrite rule to only apply to the /api/v1 path

-- Joelgullander
kubernetes
kubernetes-ingress
nginx-ingress

1 Answer

10/16/2019

I guess this should work for you -

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
    namespace: default
    name: my-ingress
    annotations:
       kubernetes.io/ingress.class: nginx
       nginx.ingress.kubernetes.io/rewrite-target: $1
spec:
  rules:
    - host: hostname.com
      http:
        paths:
          - path: /(.*)
            backend:
              serviceName: frontend
              servicePort: 80
          - path: /api/(.*)
            backend:
              serviceName: backend
              servicePort: 80

I have just edited this, it works for me, please check for this. I guess we can troubleshoot

-- Tushar Mahajan
Source: StackOverflow