Ingress service - different rewrites

12/20/2019

I have ingress service with the fallowing config:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - http:
        paths:
          - path: /api/?(.*)
            backend:
              serviceName: my-service
              servicePort: 3001
          - path: /auth/?(.*)
            backend:
              serviceName: my-service
              servicePort: 3001

The thing is that when I'm running this on my minikube I cannot connect in a proper way, ie. When I'm typing in the browser: IP/api/test it shows not found even though my express endpoint is:

app.get('/api/test', (req, res) => {
  return res.send({ hi: 'there' });
});

But IP/api/api/test (double api) works and delivers expected response. Obviously I would like to get there with IP/api/test. How can I achieve that in my ingress config?

-- Murakami
kubernetes
nginx-ingress

2 Answers

12/20/2019

If You want to access http://.../api/test by calling curl http://.../api/test than you don't need a rewrite for it so just make it empty.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - http:
        paths:
          - path: /?(.*)
            backend:
              serviceName: my-service
              servicePort: 3001
          - path: /auth/?(.*)
            backend:
              serviceName: my-service
              servicePort: 3001

This configuration will for example rewrite the following:

http://.../api/test -> http://.../api/test
http://.../auth/test -> http://.../test
http://.../asdasdasd -> http://.../asdasdasd

Update:

In case You have another rewrite with path: /?(.*) You can modify Your app path request to:

app.get('/test', (req, res) => {
  return res.send({ hi: 'there' });
});

and use the original ingress configuration You posted in Your question.

This way when the request You have issues with will be resolved in following way:

IP/api/test -> IP/test

This is also the reason why You experienced IP/api/api/test before. Because one /api/ was removed by rewrite and then IP/api/test was accessible.

Yes, You can have multiple rewrites in ingress. As long as they don't loop or rewrite too many times.

-- Piotr Malec
Source: StackOverflow

12/20/2019

It's the rewrite-target messing with your api link, change that to nginx.ingress.kubernetes.io/rewrite-target: / and you can directly communicate with the /api/endpoint.

As this example explains it, and you can also see that it is appending the placeholder from your url with rewrite-target: /app.

Hope this helps.

-- BinaryMonster
Source: StackOverflow