"WWW" to "Non-WWW" redirect using request variables with Traefik?

Viewed 3381

I apologize in advance for my novice understanding with Traefik, but is there a way to rewrite to "non-www" domains with a request-based variable?

I've been Googling for over an hour and cannot find an answer.

Here is an example how I would do this in Apache. You can see it is using the HTTP_HOST variable:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

I can see that I can set labels like so:

--label "traefik.frontend.redirect.permanent=true" 
--label "traefik.frontend.redirect.regex=^https?://www.example.com/(.*)"
--label "traefik.frontend.redirect.replacement=https://example.com/${1}"

But this requires me to set example.com for everything. I would like this to redirect regardless of the domain. Thanks!

2 Answers

I found some help in the Traefik Slack group and a user pointed me in the right direction. Using their documentation (https://docs.traefik.io/configuration/entrypoints/#rewriting-url), he was able to help me write regular expressions that solved my need:

[entryPoints.https.redirect]
permanent=true
regex = "^https://www.(.*)"
replacement = "https://$1"

This is the setup that worked for me with docker:

  service-a:
    labels:
      - "traefik.http.routers.service-a.rule=Host(`example.com`) || Host(`www.example.com`)"
      - "traefik.http.middlewares.service-a-redirect.redirectregex.regex=^(https?://)www.(.*)$$"
      - "traefik.http.middlewares.service-a-redirect.redirectregex.replacement=$${1}$${2}"
      - "traefik.http.routers.service-a.middlewares=service-a-redirect"

It supports both http and https.

Inspired by: https://medium.com/better-programming/traefik-2-1-as-a-reverse-proxy-c9e274da0a32

Related