"WWW" 到 "Non-WWW" 使用 Traefik 请求变量重定向?

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

对于我对 Traefik 的新手理解,我提前表示歉意,但是有没有办法用基于请求的变量重写到"non-www"域

我在谷歌上搜索了一个多小时,但找不到答案。

这是我如何在 Apache 中执行此操作的示例。您可以看到它正在使用 HTTP_HOST 变量:

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

我可以看到我可以像这样设置标签:

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

但这需要我为所有内容设置 example.com。无论域如何,我都希望重定向。谢谢!

我在 Traefik Slack 组中找到了一些帮助,一位用户为我指明了正确的方向。使用他们的文档 (https://docs.traefik.io/configuration/entrypoints/#rewriting-url),他能够帮助我编写满足我需求的正则表达式:

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

这是对我适用的设置 docker:

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

它同时支持httphttps

灵感来自:https://medium.com/better-programming/traefik-2-1-as-a-reverse-proxy-c9e274da0a32