我最近将我的个人博客的托管服务提供商从Netlify切换到了我的自定义堆栈(Docker、Portainer和Traefik),我很快注意到我在迁移中忘记了一些东西:从benjaminrancourt.ca到www.benjaminrancourt.ca...😟

尽管我的网站包含个规范链接元素并且为两个域提供了同一个网站,但让我感到困扰的是我失去了这个小功能......所以很自然地,我开始在互联网上搜索如何使用 Traefik 实现这个重定向. 😇

Unfortunately, although the Traefik community has asked similar questions several times in the past (5425, 6458, 6813, 8409, 7428, 8976 and 10711),建议的解决方案都不适用于我的环境......😢

他们中的大多数人用labels定义了一个新的中间件,但我一直在寻找一个更全局的解决方案,我只能应用于某些站点。我认为创建一个新的中间件来解决每个需要它的网站的重定向不是很有效......🤔

特别是,解决方案并不完全相同,但它们彼此相似:

  - "traefik.http.middlewares.wwwtohttps.redirectregex.regex=^https?://(?:www\\.)?(.+)"
  - "traefik.http.middlewares.wwwtohttps.redirectregex.replacement=https://$${1}"
  - "traefik.http.middlewares.wwwtohttps.redirectregex.permanent=true"

进入全屏模式 退出全屏模式

他们中的一些人逃脱了两次(\\.),而其他人只逃脱了一次(\.),而其他人则没有逃脱(.)......双美元符号也有两种变体($${1}${1})...... . 哪一个是正确的?有点混乱,对吧? 😵

所以我开始尝试几种组合,在几次破坏我的现场网站后,我终于让它工作了!以下是适用于 Traefik v2.5.1 的解决方案。 🎉

解决方案

正如我上面所说,我只定义了一次中间件,在动态配置文件中:

# Traefik dynamic configuration file
# See https://doc.traefik.io/traefik/getting-started/configuration-overview/#the-dynamic-configuration

http:
  middlewares:
    # Redirect non-www URLs to their www equivalent
    # Use with traefik.http.routers.myRouter.middlewares: "redirect-non-www-to-www@file"
    redirect-non-www-to-www:
      # Redirect a request from an url to another with regex matching and replacement
      redirectregex:
        # Apply a permanent redirection (HTTP 301)
        permanent: true
        # The regular expression to match and capture elements from the request URL
        regex: "^https?://(?:www\\.)?(.+)"
        # How to modify the URL to have the new target URL
        replacement: "https://www.${1}"

    # Redirect www URLs to their non-www equivalent
    # Use with traefik.http.routers.myRouter.middlewares: "redirect-www-to-non-www@file"
    redirect-www-to-non-www:
      # Redirect a request from an url to another with regex matching and replacement
      redirectregex:
        # Apply a permanent redirection (HTTP 301)
        permanent: true
        # The regular expression to match and capture elements from the request URL
        regex: "^https?://www\\.(.+)"
        # How to modify the URL to have the new target URL
        replacement: "https://${1}"

进入全屏模式 退出全屏模式

您可能已经注意到如何在我的评论中使用它们,但只需向您的docker-compose.yml文件添加一个新标签:

  traefik.http.routers.myRouter.middlewares: "redirect-non-www-to-www@file"

进入全屏模式 退出全屏模式

如果你的路由器已经有一个中间件,只需添加你想要的中间件,用逗号 (,) 分隔它们,比如another-middleware,redirect-non-www-to-www@file

就是这样,您现在可以将您的网站重定向到 www 或非www。 🤗

Logo

CI/CD社区为您提供最前沿的新闻资讯和知识内容

更多推荐