Enable global middleware for www to non www redirect

I would like to create a global www to non www middleware, I configured it but when I look into the dashboard it doesn't show up under middlewares, and the redirect also doesn't work, so I think traefik doesn't recognize the middelware at all.

This is my config, under trafik - labels I added this:

   - "traefik.http.middlewares.nonwww.redirectregex.regex=^https?://(?:www.)?(.+)"
   - "traefik.http.middlewares.nonwww.redirectregex.replacement=https://$${1}"

and this is the config for my domain, what I want to achieve is that www redirects to non-www

    image: traefik/whoami
     - "--port=8084"
     - "traefik.enable=true"
     - "traefik.http.routers.r1.rule=Host(`mydomain.tld`) || Host(`www.mydomain.tld`)"
     - "traefik.http.routers.r1.entrypoints=websecure"
     - "traefik.http.routers.r1.tls=true"
     - "traefik.http.routers.r1.tls.certresolver=myresolver"
     - "traefik.http.services.r1.loadbalancer.server.port=8084"

You must assign your middleware to your router, see docs with example.

You can configure a global redirect easily for all services with a single entrypoint redirection.

I tried this before like in the example, I added

  • "traefik.http.routers.r1.middlewares=nonwww@docker"

however, in the dashboard I'm getting the error

middleware "nonwww@docker" does not exist

This works for me:

      - traefik.http.middlewares.mywwwremove.redirectregex.regex=^https://www\.(.*)
      - traefik.http.middlewares.mywwwremove.redirectregex.replacement=https://$${1}

    image: traefik/whoami:v1.8
      - proxy
      - traefik.enable=true
      - traefik.http.routers.whoami.entrypoints=websecure
      - traefik.http.routers.whoami.rule=Host(`whoami.example.com`) || Host(`www.whoami.example.com`)
      - traefik.http.routers.whoami.tls.certresolver=myresolver
      - traefik.http.routers.whoami.middlewares=mywwwremove
      - traefik.http.services.whoami.loadbalancer.server.port=80

Note: entrypoint redirection can only change to https protocol.