【问题标题】:Traefik redirect from one host to anotherTraefik 从一台主机重定向到另一台主机
【发布时间】:2020-03-04 14:31:31
【问题描述】:

我们决定从子域结构转移到一个带有路径前缀的根域,但我们在互联网上得到了许多旧 URL。那么有什么办法可以将旧网址的重定向添加到新网址? 例如, 我们将子域 test.example.com 切换到 example.com/test,我可以使用 docker-swarm YAML 文件中的字符串正确访问站点 traefik.frontend.rule: Host:example.com;PathPrefixStrip:/test 但是当我尝试添加到 Traefik 配置重定向时,例如:

[http.middlewares]
  [http.middlewares.test-redirectregex.redirectRegex]
    regex = "^https://(*).example.com/)"
    replacement = "^https://example.com/${1}"

Traefik 说它不知道将这个请求转发到哪里 如果我要添加: traefik.frontend.rule: Host:test.example.com,example.com;PathPrefixStrip:/test Traefik 为两个主机添加前缀。有没有办法在不添加第二个反向代理的情况下解决这个问题?

【问题讨论】:

  • 你使用的是 traefik 2.1 吗?

标签: redirect reverse-proxy docker-swarm traefik


【解决方案1】:

假设你使用的是 Traefik 2.1,你可以使用下面的 Traefik 中间件

[http.middlewares]
  [http.middlewares.blog-redirect.redirectRegex]
    regex = "^(https?://)(.*).example.com/(.*)$"
    replacement = "${1}example.com/${2}/${3}"
    permanent = true

激活上述中间件的重要步骤是在相应的路由器和服务上添加以下标签。例如,如果您有一个blog 服务并为它定义了一个blog 路由器,那么您需要将下表添加到服务中

traefik.http.routers.blog.middlewares=blog-redirect

此外,您的路由规则应类似于以下规则,以便能够处理两个域(或者您为每个服务定义多个路由)

- traefik.http.routers.blog.rule=Host(`example.com`) && Path(`/test`) || Host(`api.example.com``) 

在这个post,你可以找到更多关于流量和重定向的信息

【讨论】: