Search code examples
traefik

Traefik - apply middleware to router except a specific path


I use a IP whitelist middleware to filter the access of my web application to some IPS only and it works.

But, I want to unprotect a specific path to make it public (the path is /api/transaction).

For now, I have (in my docker-comose.yml) :

varnish:
  labels:
    - "traefik.http.routers.api_varnish.rule=Host(`api.local`, `api`)"
    - "traefik.http.routers.api_varnish.tls=true"
    - "traefik.http.routers.api_varnish.middlewares=https-redirect@file"
    - "traefik.http.routers.api_varnish.middlewares=https-whitelist@file"
    - "traefik.http.services.api_varnish.loadbalancer.server.port=80"

This part works, then I added:

    # Open middleware for payment IPN calls
   - "traefik.http.routers.api_varnish_transaction.rule=(Host(`api.local`, `api`) && PathPrefix(`/api/transaction`))"
   - "traefik.http.routers.api_varnish_transaction.tls=true"
   - "traefik.http.routers.api_varnish_transaction.priority=2"
   - "traefik.http.routers.api_varnish_transaction.middlewares=https-redirect@file"

I duplicated the lines, but I didn't apply the middleware https-whitelist@file to the new host.

It doesn't work, I can't find the correct syntax or be sure if I can do it ? documentation is pretty poor.

Any idea?


Solution

  • Have 2 routers:

    • router-api: /api/transaction, and give this a higher priority (set a higher number)
    • router: for /*
    # ...
        labels:
          - traefik.enable=true
          - traefik.http.routers.router.rule=Host(`api.local`)
          - traefik.http.routers.router.priority=1
          - traefik.http.middlewares...theoneyouwantapplied..
          - traefik.http.routers.router.middlewares=test-auth
          - traefik.http.routers.router.service=server
          - traefik.http.routers.router-api.rule=(Host(`api.local`) && PathPrefix(`/api`))
          - traefik.http.routers.router-api.priority=3
    

    Now requests to /api/transaction will only hit router_1

    https://doc.traefik.io/traefik/routing/routers/#priority