Redirect naked to www

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

I found many examples here, on StackOverflow and Reddit, but most were for the inverse case (www -> naked). Those for this case (naked -> www) seem to be for an older version (pre-2020 / v1). I also studied the docs but found nothing.

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

Then for some 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?

Use two separate routers for www and non-www and only apply the redirect middleware to the non-www router.

1 Like

Thanks! I should have thought of that, that's how it's done in nginx with two server blocks.

I could find no other working examples for this use case, so I hope this helps someone else:

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}`)

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