如何使用 Traefik 强制 www

How to force www with Traefik

我一直在学习 Traefik 作为服务器上 Docker 容器中的各种 Wordpress 站点的反向代理 运行。目前我在同一 IP 上使用 Wp 设置了 2 个域并且工作正常。

我在将域重定向到 www 时遇到问题,所以现在 http://example.com 它只是显示 'Index of' 我已经尝试通过 htaccess 强制重定向,但是这不起作用所以我假设我有一些东西必须在 Traefik 设置中做什么?

这是我的 docker-compose.yml 文件,但我只在此处包含重要部分:

services:
  reverse-proxy:
    image: traefik # The official Traefik docker image
    command: --api --docker # Enables the web UI and tells Træfik to listen to docker
    ports:
      - "80:80"     # The HTTP port
      - "8080:8080" # The Web UI (enabled by --api)
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock # So that Traefik can listen to the Docker events
      - ./traefik.toml:/traefik.toml

wp-web2:
    container_name: cowork-wp
    image: wordpress:latest
    restart: always
    environment:
      WORDPRESS_DB_HOST: mysql-db-cowork
      WORDPRESS_DB_USER: foo
      WORDPRESS_DB_NAME: foo
      WORDPRESS_DB_PASSWORD: passwd123
    depends_on:
      - mysql-db-cowork
    labels:
      - "traefik.frontend.rule=Host:example.com"
      - "traefik.frontend.rule=Host:www.example.com"
      - "traefik.frontend.forcehost:www.example.com"
      #- "traefik.frontend.rule=Path: /"
    volumes:
      - ./src-tdm:/var/www/html

正如您在标签中看到的,我一直在尝试不同的主机以及 'forcehost',但其中 none 似乎有效。

这是 toml 文件:

defaultEntryPoints = ["http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"

#Define Docker Backend Configuration
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "example.com"
watch = true
exposedByDefault = true

最后这是我从 .htaccess

强制 www 重写规则
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com [L,R=301,NC]

仔细查看文档后发现,需要在前端 Host: 参数中用逗号定义不同的域,例如:

- "traefik.frontend.rule=Host:www.example.com, example.com"