将naked重定向到www使用traefik

huangapple go评论55阅读模式
英文:

Redirect naked to www with traefik

问题

I want to redirect example.com to www.example.com.

In the traefik container's docker-compose.yml, I defined a redirection middleware that I can use from multiple services:

traefik:
  image: traefik
  # ...
  labels:
    traefik.http.middlewares.nakedtowww.redirectregex.regex: ^https?://(?:www\.)?(.+)
    traefik.http.middlewares.nakedtowww.redirectregex.replacement: https://www.$
    traefik.http.middlewares.nakedtowww.redirectregex.permanent: true

And a service:

whoami:
  image: traefik/whoami
  # ...
  labels:
    traefik.enable: true
    traefik.http.routers.whoami.rule: Host(`${DOMAIN}`, `www.${DOMAIN}`)
    traefik.http.routers.whoami.middlewares: nakedtowww

When I visit either https://example.com or https://www.example.com it redirects to https://www.www.example.com and responds with 404.

How do I fix it?

英文:

I want to redirect example.com to www.example.com.

In the traefik container's docker-compose.yml, I defined a redirection middleware that I can use from multiple services:

traefik:
  image: traefik
  # ...
  labels:
    traefik.http.middlewares.nakedtowww.redirectregex.regex: ^https?://(?:www\\.)?(.+)
    traefik.http.middlewares.nakedtowww.redirectregex.replacement: https://www.$
    traefik.http.middlewares.nakedtowww.redirectregex.permanent: true

And a service:

whoami:
  image: traefik/whoami
  # ...
  labels:
    traefik.enable: true
    traefik.http.routers.whoami.rule: Host(`${DOMAIN}`, `www.${DOMAIN}`)
    traefik.http.routers.whoami.middlewares: nakedtowww

When I visit either https://example.com or https://www.example.com it redirects to https://www.www.example.com and responds with 404.

How do I fix it?

答案1

得分: 0

一定要定义两个路由器:

whoami:
  image: traefik/whoami
  # ...
  labels:
    # naked -> www
    traefik.http.routers.whoami-naked.entrypoints: websecure
    traefik.http.routers.whoami-naked.rule: Host(`${DOMAIN}`)
    traefik.http.routers.whoami-naked.middlewares: nakedtowww
    # www
    traefik.http.routers.whoami-www.entrypoints: websecure
    traefik.http.routers.whoami-www.rule: Host(`www.${DOMAIN}`)
英文:

One must define two routers:

whoami:
  image: traefik/whoami
  # ...
  labels:
    # naked -> www
    traefik.http.routers.whoami-naked.entrypoints: websecure
    traefik.http.routers.whoami-naked.rule: Host(`${DOMAIN}`)
    traefik.http.routers.whoami-naked.middlewares: nakedtowww
    # www
    traefik.http.routers.whoami-www.entrypoints: websecure
    traefik.http.routers.whoami-www.rule: Host(`www.${DOMAIN}`)

huangapple
  • 本文由 发表于 2023年6月8日 15:04:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定