Setup URL Redirect in Traefik

/ 312 words / docker guide linux

This article will help you setup a redirect from your old domain to a new one without an external service using Traefik.

Official Traefik documentation can be confusing at times and some stuff that we will be using today is completely missing from it, so I thought writing an article might help some people in the future.

Assumptions:

Prerequisites:

If you don’t meet the prerequisites, you can check my example Traefik configuration here. (GitHub Repository)

You will want to start by adding a new middleware to your dynamic Traefik configuration file, in my case dynamic.yml.

# dynamic configuration file
http:
  middlewares:
    redirect-new-domain:
      redirectregex:
        # redirect everything
        regex: ".*"
        # new domain redirect
        replacement: "https://new-example.com"

You can declare that the redirect is permanent by adding permanent: true in your redirectregex middleware.

Now after you’ve setup your new middleware, you will want to add a new route in the same file:

# dynamic configuration file
http:
  routers:
    example-com:
      # change to your entrypoint!
      entrypoints: websecure
      # regex to include all subdomains
      rule: HostRegexp(`example.com`,`{subdomain:.*}.example.com`) 
      # redirect middleware
      middlewares: redirect-new-domain
      # dummy service from traefik
      service: noop@internal
      tls:
        # adjust to your certresolver
        certresolver: cloudflare 

And that’s it! Traefik will now redirect all requests from your old domain (example.com, *.example.com) to your new domain (new-example.com).

I’ve included an example of the Traefik dynamic configuration file below.

# final example of dynamic configuration file
http:
  routers:
    example-com:
      # change to your entrypoint!
      entrypoints: websecure
      # regex to include all subdomains
      rule: HostRegexp(`example.com`,`{subdomain:.*}.example.com`) 
      # redirect middleware
      middlewares: redirect-new-domain
      # dummy service from traefik
      service: noop@internal
      tls:
        # adjust to your certresolver
        certresolver: cloudflare 

  middlewares:
    redirect-new-domain:
      redirectregex:
        # redirect everything
        regex: ".*"
        # new domain redirect
        replacement: "https://new-example.com"