Search code examples
lets-encrypttraefikhttp-redirect

Traefik Redirect Domain to Subdomain


I want to permanently redirect all requests to example.com and www.example.com to blog.example.com in a TLS environment.

My current config:

traefik.toml:

[entryPoints]
  [entryPoints.web]
    address = ":80"
    [entryPoints.web.http.redirections.entryPoint]
      to = "websecure"
      scheme = "https"

  [entryPoints.websecure]
    address = ":443"

[providers.docker]
  exposedbydefault = false
  watch = true
  network = "web"
[providers.file]
  filename = "traefik_dynamic.toml"

[certificatesResolvers.lets-encrypt.acme]
  email = "[email protected]"
  storage = "/letsencrypt/acme.json"
  [certificatesResolvers.lets-encrypt.acme.dnsChallenge]
    provider = "myprovider"

traefik_dynamic.toml:

[http.middlewares] 
  [http.middlewares.goToBlog.redirectregex] 
    regex = "^https://(.*)example.com/(.*)" 
    replacement = "https://blog.example.com/$${2}"
    permanent = true
 
[http.routers] 
  [http.routers.gotoblog] 
    rule = "Host(`example.com`) || Host(`www.example.com`)" 
    entrypoints = ["websecure"] 
    middlewares = ["goToBlog"] 
    service = "noop@internal" 
    [http.routers.gotoblog.tls] 
      certResolver = "lets-encrypt"

When I try to access example.com it gives my an SSL Protocol Error. All my other endpoints including blog.example.com are working. What am I doing wrong?


Solution

  • Okey, obviously it had nothing to do with my redirect configuration. Seemed like a hickup in traefik / docker, similar to ACME certificates timeout with traefik. Just waited one day and everything worked as expected. Just two minor updates to correct the redirect configuration. Maybe there's a more elegant solution.

    traefik_dynamic.toml:

    [http.middlewares] 
      [http.middlewares.goToBlog.redirectregex] 
        regex = "^https://(.*)example.com/(.*)" 
        replacement = "https://blog.example.com/${2}"         # no double $$
        permanent = true
     
    [http.routers] 
      [http.routers.gotoblog] 
        rule = "Host(`example.com`, `www.example.com`)"       # just an array of domains is fine, too
        entrypoints = ["websecure"] 
        middlewares = ["goToBlog"] 
        service = "noop@internal" 
        [http.routers.gotoblog.tls] 
          certResolver = "lets-encrypt"