A lot of people are still used to a website needing to start with www. but this is not the case anymore. This has created a few issues in the past where I would deploy a site to https://my-site.org but then when people would try to share the site they would mention it as https://www.my-site.org.

Making the site available on both !

So I first started looking at how to make the site available on both those URLs. The first thing that came to mind was altering the Traefik labels attached to the Docker container serving the site.

# docker-compose.yaml
version: '3.7'
      - "traefik.enable=true"
      - "traefik.http.routers.my-site.rule=Host(`my-site.org`) || Host(`www.my-site.org`)"

This works and the site becomes available on both of the URLs, great all done, time to go to bed ...


The problem with that was site crawlers considering the data on the site as duplicated, and they really do not like that. To avoid having this happen we need to make sure that anyone or anything trying to go to a page starting with www. get automatically, and permanently redirected to the page without that sub-domain.

I first started by running a small nGinx instance in another container labeled with the www. prefix that would return a 301 to the actual site. This was a bit hacky and started to become annoying to do for every site.

Depending on the Host where the site is registered to I could also sometimes add a redirect to the DNS settings but not always and this would always be a lot of clicking around.

Luckily reading through the updates happening withing Traefik I found something.

Traefik redirection middlewares

I came upon the RedirectRegex middleware section of the documentation. It states that if the incoming request matches a regex we replace the url of the request. So I figured I would give this a shot to get rid of the www subdomain.

There are many ways to add middlewares to your Traefik configuration but as this one will become required more and more often I did not want to add many more labels to every Docker container. I ended up adding it to my dynamic_conf.yaml file.

         regex: "^https?://www\\.(.+)"
         replacement: "https://${1}"
         permanent: true

There it is ! Anything that starts with http://www. or https://www. will get permanently redirected to https://

http://www.my-site.org => https://my-site.org

So now if I need one of my containers to use this middleware I will have to add another label :

      - "traefik.enable=true"
      - "traefik.http.routers.my-site.rule=Host(`my-site.org`) || Host(`www.my-site.org`)"
      - "traefik.http.routers.my-site.middlewares=redirect-www@file"


  • 17/03/2021 : Update the regex from ^https?://www.(.*) to ^https?://www\\.(.+) thanks to Navossoc 's comments