Multiple Rules on IngressRoute to route to two different services based on Path

How do I configure my IngressRoute to route to different services based on the path? For example, if my app is on myapp-ui.example.org and I want all requests on the root (/ or myapp-ui.example.org/) to go to one service and all requests that go to /api (or myapp-ui.example.org/api/), how do I define the rules in the IngressRoute?

So far, I have something like this but it does not seem to work:

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: frontend-ingress
spec:
  entryPoints:
    - web
  routes:
    - kind: Rule
      match: Host(`myapp-ui.example.org`)
      services:
        - kind: Service
          name: frontend-service
          passHostHeader: true
          port: 80
    - kind: Rule
      match: Host(`myapp-ui.example.org`) && Path(`/api`)
      services:
        - kind: Service
          name: api-service
          passHostHeader: true
          port: 80

Hello, I'm facing the same problem, did you find the solution?

I don't know if this is the best or preferred way in respect to Traefik, but it worked for me:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: stripprefix
spec:
  stripPrefix:
    prefixes:
      - /api
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: frontend-ingress
spec:
  entryPoints:
    - web
  routes:
    - kind: Rule
      match: Host(`myapp-ui.example.org`) && PathPrefix(`/`)
      services:
        - kind: Service
          name: frontend
          passHostHeader: true
          port: 80
    - kind: Rule
      match: Host(`myapp-ui.example.org`) && PathPrefix(`/api`)
      services:
        - kind: Service
          name: api-service
          port: 80
      middlewares:
        - name: stripprefix

Good Luck!

1 Like

Hello @cj1

This is exactly what the middleware StripPrefix has been designed for.

Thank you for using Traefik!