RedirectRegex
RedirectRegex 使用正则表达式匹配和替换来重定向请求。
配置示例¶
# Redirect with domain replacement
http:
middlewares:
test-redirectregex:
redirectRegex:
regex: "^http://localhost/(.*)"
replacement: "http://mydomain/${1}"# Redirect with domain replacement
[http.middlewares]
[http.middlewares.test-redirectregex.redirectRegex]
regex = "^http://localhost/(.*)"
replacement = "http://mydomain/${1}"# Redirect with domain replacement
# Note: all dollar signs need to be doubled for escaping.
labels:
- "traefik.http.middlewares.test-redirectregex.redirectregex.regex=^http://localhost/(.*)"
- "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$${1}"// Redirect with domain replacement
// Note: all dollar signs need to be doubled for escaping.
{
// ...
"Tags" : [
"traefik.http.middlewares.test-redirectregex.redirectregex.regex=^http://localhost/(.*)"
"traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$${1}"
]
}# Redirect with domain replacement
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-redirectregex
spec:
redirectRegex:
regex: ^http://localhost/(.*)
replacement: http://mydomain/${1}配置选项¶
| 字段 | 说明 | 默认值 | 必填 |
|---|---|---|---|
regex |
regex 选项是用于从请求 URL 中匹配并捕获内容的正则表达式。 |
"" | 是 |
permanent |
启用永久重定向。 | false | 否 |
replacement |
replacement 选项定义如何修改 URL,以获得新的目标 URL。$1x 等同于 ${1x},而非 ${1}x(参阅 Regexp.Expand),因此应使用 ${1} 语法。 |
"" | 否 |
regex 正则表达式¶
regex 选项是用于从请求 URL 中匹配并捕获内容的正则表达式。
提示
可以使用 Go Playground 或 Regex101 等在线工具测试正则表达式和替换规则。
在 YAML 中定义正则表达式时,任何需要转义的字符都必须转义两次:example\.com 应写成 example\\.com。
replacement 替换规则¶
replacement 选项定义如何修改 URL,以获得新的目标 URL。
警告
定义替换展开变量时应格外留意:$1x 等同于 ${1x},而非 ${1}x(参阅 Regexp.Expand),因此应使用 ${1} 语法。
在生产环境使用 Traefik OSS?
如果你在工作中使用 Traefik,可以考虑为 Traefik OSS 增加企业级 API 网关能力或商业支持。
为 Traefik OSS 增加 API 网关能力快捷且平滑,无需推倒重来,现有配置也会完整保留。请通过这个简短视频了解实际效果。