http-redirectreverse-proxytraefiktraefik-middlewaretraefik-routers

Redirect naked to www with traefik


I want to redirect example.com to www.example.com.

In the traefik container's docker-compose.yml, I defined a redirection middleware that I can use from multiple services:

traefik:
  image: traefik
  # ...
  labels:
    traefik.http.middlewares.nakedtowww.redirectregex.regex: ^https?://(?:www\\.)?(.+)
    traefik.http.middlewares.nakedtowww.redirectregex.replacement: https://www.$${1}
    traefik.http.middlewares.nakedtowww.redirectregex.permanent: true

And a service:

whoami:
  image: traefik/whoami
  # ...
  labels:
    traefik.enable: true
    traefik.http.routers.whoami.rule: Host(`${DOMAIN}`, `www.${DOMAIN}`)
    traefik.http.routers.whoami.middlewares: nakedtowww

When I visit either https://example.com or https://www.example.com it redirects to https://www.www.example.com and responds with 404.

How do I fix it?


Solution

  • One must define two routers:

    whoami:
      image: traefik/whoami
      # ...
      labels:
        # naked -> www
        traefik.http.routers.whoami-naked.entrypoints: websecure
        traefik.http.routers.whoami-naked.rule: Host(`${DOMAIN}`)
        traefik.http.routers.whoami-naked.middlewares: nakedtowww
        # www
        traefik.http.routers.whoami-www.entrypoints: websecure
        traefik.http.routers.whoami-www.rule: Host(`www.${DOMAIN}`)