Nginx ingress rule for changing path on the fly

7/19/2019

I would like to change the path of request coming to ingress-nginx on the fly to match what different backend services expect. For example, imagine these are the two services I have got:

foo service:

http://foo:8080/api/v1

bar service:

http://bar:8080/api/v1

I would like to expose foo service as http://test.com/foo/api and bar service as http://test.com/bar/api. However, I am not sure how I can change the path on the fly to match what the underlying service expects.

Example ingress.yaml file:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress

spec:
  rules:
    - host: test.com
      http:
        paths:
          - path: /foo/api/
            backend:
              serviceName: foo
              servicePort: 8080
          - path: /bar/api
            backend:
              serviceName: bar
              servicePort: 8080
          - path: /
            backend:
              serviceName: ui
              servicePort: 80
-- Ali
kubernetes-ingress
nginx
nginx-ingress

1 Answer

7/19/2019

You can try with rewrite annotations.

Look at the example provided in this documentation:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: http-svc
          servicePort: 80
        path: /something(/|$)(.*)

In this ingress definition, any characters captured by (.*) will be assigned to the placeholder $2, which is then used as a parameter in the rewrite-target annotation.

For example, the ingress definition above will result in the following rewrites:

  • rewrite.bar.com/something rewrites to rewrite.bar.com/
  • rewrite.bar.com/something/ rewrites to rewrite.bar.com/
  • rewrite.bar.com/something/new rewrites to rewrite.bar.com/new

Just adjust the path and other variables with your data.

Please let me know if that helped.

-- OhHiMark
Source: StackOverflow