使用Traefik使用请求变量将“ WWW”重定向到“非WWW”?

时间:2019-01-12 17:24:15

标签: traefik

对于我对Traefik的新手了解,我预先道歉,但是有没有办法使用基于请求的变量来重写“非www”域?

我已经谷歌搜索了一个多小时,找不到答案。

这是我将如何在Apache中执行此操作的示例。您可以看到它正在使用print( next(iter( mydict.items() )) ) # ('Key1', 'Value1') 变量:

HTTP_HOST

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

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$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/${1}" 。我想重定向到任何域。谢谢!

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这是适用于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=$${1}$${2}"
      - "traefik.http.routers.service-a.middlewares=service-a-redirect"

它同时支持httphttps

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