Nested Path Prefix Traefik

I am trying to create a reverse proxy, that should map the following routes

http://<host>/api/foo -> service_1
http://<host>/api/bar -> service_2

I have the following dynamic configuration:

http:
  routers:
    to-foo:
      rule: PathPrefix(`/api/foo/`)
      ...
    to-bar:
      rule: PathPrefix(`/api/bar/`)
      ...
  ...

With the above dynamic configuration only the bottom one ist mapped accordingly. api/foo returns a 404.
I have also tried the following rule:

PathPrefix(`api`, `foo`)

However, when routing to /api/foo, I am now proxied to the service of /api/bar.

Does anyone know how to get this setup working with nested routes? Can I somehow create a router parent for api routes, and handle it that way? Or is this not currently possible with traefik, should I rather create a mapping, such as the following: /api-foo?

Hello @Keimeno,

I got it working:

version: '3.6'

services:
  traefik:
    image: traefik:v2.6
    command:
      - --providers.docker
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  whoami-foo:
    image: traefik/whoami
    command: -name foo
    labels:
      traefik.http.routers.whoami-foo.rule: PathPrefix(`/api/foo`)

  whoami-bar:
    image: traefik/whoami
    command: -name bar
    labels:
      traefik.http.routers.whoami-bar.rule: PathPrefix(`/api/bar`)

  whoami-api:
    image: traefik/whoami
    command: -name api
    labels:
      traefik.http.routers.whoami-api.rule: PathPrefix(`/api`)

With this, I can do:

> curl localhost/api | jq .name # /api is a special path on whoami
"api"
> curl localhost/api/bar | grep Name
Name: bar
> curl localhost/api/foo | grep Name
Name: foo

WDYT ?

Thanks for the response, after rebuilding my dynamic config it started working as expected. I must have had a syntax error somewhere.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.