运维相关 · 2022年7月21日 0

Traefik全局http跳转https,以及去除www

traefik版本v2.8.1

分两种模式,配置文件模式和命令模式

配置文件模式如下:

entryPoints:
  web:
    address: :80
    # global redirect to https
    http:
      redirections:
        entryPoint:
          to: websecure
          scheme: https
          permanent: true
  websecure:
    address: :443
http:
  middlewares:
    redirect-to-nonwww:
      redirectRegex:
        regex: "^https?://(?:www\\.)?(.+)"
        replacement: "https://${1}"
        permanent: true

    gzip-compress:
      compress:
        excludedContentTypes:
          - text/event-stream

命令模式如下:

version: "3.3"
networks:
  work-net:
    external: true
    
services:
  traefik:
    image: traefik:latest
    container_name: traefik
    restart: always
    command:
      # http
      - --entrypoints.web.address=:80
      # global redirect to https
      - --entrypoints.web.http.redirections.entryPoint.to=websecure
      - --entrypoints.web.http.redirections.entryPoint.scheme=https
      # https
      - --entrypoints.websecure.address=:443
      # 忽略后端证书验证
      - --serversTransport.insecureSkipVerify=true
      # 禁止自动发现容器并代理
      - --providers.docker.exposedByDefault=false
      - --log.level=ERROR
      # 证书申请配置
      - --certificatesresolvers.leresolver.acme.httpchallenge=true
      - [email protected] 
      - --certificatesresolvers.leresolver.acme.storage=/acme/acme.json
      - --certificatesresolvers.leresolver.acme.httpchallenge.entrypoint=web
    ports:
      - "80:80"
      - "443:443"
    networks:
      - work-net
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - "acme:/acme"
    labels:
      - traefik.enable=true
      # redirect to nonwww
      - traefik.http.middlewares.redirect-to-nonwww.redirectregex.regex=^https?://(?:www\.)?(.+)
      - traefik.http.middlewares.redirect-to-nonwww.redirectregex.replacement=https://$${1}
      # compress gzip
      - traefik.http.middlewares.gzip-compress.compress=true
      - traefik.http.middlewares.gzip-compress.compress.excludedcontenttypes=text/event-stream
volumes:
  acme:
    name: traefik_acme

使用方式

    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.wordpress-app.rule=Host(`anerg.com`, `www.anerg.com`)"
      - "traefik.http.routers.wordpress-app.tls=true"
      - "traefik.http.routers.wordpress-app.tls.certresolver=dnspod"
      - "traefik.http.routers.wordpress-app.entrypoints=websecure"
      - "traefik.http.routers.wordpress-app.service=wordpress-srv"
      - "traefik.http.services.wordpress-srv.loadbalancer.server.port=8443"
      - "traefik.http.services.wordpress-srv.loadbalancer.server.scheme=https"
      - "traefik.http.routers.wordpress-app.middlewares=redirect-to-nonwww@file,gzip-compress@file"

需要注意的是,如果使用的是命令模式的话,中间件后面的@file要改成@docker

最后的效果就会是如下的跳转逻辑

http://www.anerg.com 301-> https://www.anerg.com 301-> https://anerg.com