使用Traefik处理一些复杂的路由规则
2021-09-23 • 预计阅读时间 1 分钟
2021-09-23 • 预计阅读时间 1 分钟
Traefik有几种路由方式,一般情况下使用Host来区分服务方便.但是也可以通过Host和Path组合起来实现一些复杂的玩法.这种实现相对于Nginx的反代还是简单了许多.
| Rule | Description |
|---|---|
Headers(key, value) | 根据header中的key值进行路由 |
HeadersRegexp(key, regexp) | 根据header中的key值进行路由,其中值是根据正则来判定 |
Host(example.com, …) | 检查域名是否一致 |
HostHeader(example.com, …) | 检查域名是否一致 |
HostRegexp(example.com, {subdomain:[a-z]+}.example.com, …) | 根据正则表达式来判断域名是否一致 |
Method(GET, …) | 只路由指的method |
Path(/path, /articles/{cat:[a-z]+}/{id:[0-9]+}, …) | 根据路径的正则表达式进行路由 |
PathPrefix(/products/, /articles/{cat:[a-z]+}/{id:[0-9]+}) | 这个要求是host之后必须命中才可以. |
Query(foo=bar, bar=baz) | 查询串必须一致才可以路由 |
ClientIP(10.0.0.0/16, ::1) | 根据客户端ip进行路由,支持IPv4、IPv6和IP/CIDR |
最近增加了一个syncthing来做org-roam的资料库同步.可以以这个为例来示例一下如果通过PathPrefix路由来利用既有的host路由.
version: "3"
services:
syncthing:
image: ghcr.io/linuxserver/syncthing
container_name: syncthing
hostname: syncthing #optional
environment:
- PUID=${PUID}
- PGID=${PGID}
- TZ=Asia/Shanghai
volumes:
- ./syncthing/config:/config
- ../data/syncthing:/data
labels:
- "traefik.enable=true"
- "traefik.http.services.syncthing.loadbalancer.server.port=8384"
- "traefik.http.routers.syncthing.rule=Host(`wentao.org`) && PathPrefix(`/syncthing`)"
- "traefik.http.routers.syncthing.tls=true"
- "traefik.http.routers.syncthing.tls.domains[0].main=wentao.org"
- "traefik.http.routers.syncthing.tls.domains[0].sans=*.wentao.org"
- "traefik.http.middlewares.syncthing-regex.replacepathregex.regex=^/syncthing/(.*)"
- "traefik.http.middlewares.syncthing-regex.replacepathregex.replacement=/$$1"
ports:
- 22000:22000/tcp
- 22000:22000/udp
- 21027:21027/udp
restart: unless-stopped