Skip to content

Traefik RedirectRegex 中间件文档

RedirectRegex(正则重定向)

RedirectRegex 中间件使用正则匹配和替换来重定向请求。

配置示例

YAML 格式:

yaml
# 使用域名替换进行重定向
http:
  middlewares:
    test-redirectregex:
      redirectRegex:
        regex: "^http://localhost/(.*)"
        replacement: "http://mydomain/${1}"

TOML 格式:

toml
# 使用域名替换进行重定向
[http.middlewares]
  [http.middlewares.test-redirectregex.redirectRegex]
    regex = "^http://localhost/(.*)"
    replacement = "http://mydomain/${1}"

Labels 格式:

yaml
# 使用域名替换进行重定向
# 注意:所有美元符号需要双重转义。
labels:
  - "traefik.http.middlewares.test-redirectregex.redirectregex.regex=^http://localhost/(.*)"
  - "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$${1}"

Kubernetes 格式:

yaml
# 使用域名替换进行重定向
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
  name: test-redirectregex
spec:
  redirectRegex:
    regex: ^http://localhost/(.*)
    replacement: http://mydomain/${1}

配置选项

字段描述默认值必填
regex用于从请求 URL 中匹配和捕获元素的正则表达式。""
permanent启用永久重定向。false
replacement定义如何修改 URL 以得到新的目标 URL。$1x 等同于 ${1x},而不是 ${1}x(参见 Regexp.Expand),因此请使用 ${1} 语法。""

提示

可以使用在线工具如 Go PlaygroundRegex101 测试正则表达式和替换。


在生产环境使用 Traefik OSS?

如果你在工作中使用 Traefik,可以考虑为其添加企业级 API 网关能力或获取 Traefik OSS 的商业支持。

基于 MIT 协议发布