You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无负向预查的等效正则:Traefik RedirectRegex适配Go标准库

Traefik RedirectRegex:无负向预查实现URL排除重定向

需求说明

配置Traefik RedirectRegex中间件时,由于Go标准库正则不支持负向预查(?!),需要实现除指定URL外,其余所有URL均执行重定向的逻辑:

需要排除的URL(不重定向):

https://example.com/whatever/else
https://example.com/application/o/authorize/
https://example.com/application/o/authorize/Rand0m
https://example.com/application/o/authorize/Rand0m?abc=123
https://example.com/application/o/RaNd0m/end-session/
https://example.com/application/o/RaNd0m/end-session/Rand0m
https://example.com/application/o/RaNd0m/end-session/Rand0m?abc=123

需要重定向的URL示例:

https://example.com/application/o/RaNd0m/
https://example.com/application/o/RaNd0m/Rand0m
https://example.com/application/o/token/
https://example.com/application/o/token/Rand0m
https://example.com/application/o/userinfo/
https://example.com/application/o/userinfo/Rand0m
https://example.com/application/o/introspect/
https://example.com/application/o/introspect/Rand0m
https://example.com/application/o/revoke/
https://example.com/application/o/revoke/Rand0m
https://example.com/application/o/device/
https://example.com/application/o/device/Rand0m
https://example.com/application/o/RaNd0m/jwks/
https://example.com/application/o/RaNd0m/jwks/Rand0m

解决方案

利用Traefik RedirectRegex支持的反向匹配(正则前加!前缀),先写出匹配所有需排除URL的Go兼容正则,反向匹配即可实现“排除这些URL,其余重定向”的逻辑。

1. 匹配需排除URL的正则(Go语法兼容)

^https?://[^/]+/(whatever/else|application/o/(authorize(/.*)?|[^/]+/end-session(/.*)?))$

正则解析:

  • ^https?://[^/]+/:匹配HTTP/HTTPS协议及域名部分
  • whatever/else:直接匹配第一个排除路径
  • application/o/(authorize(/.*)?|[^/]+/end-session(/.*)?):匹配application/o/下的两类合法路径:
    • authorize(/.*)?:匹配authorize开头的所有子路径(含参数)
    • [^/]+/end-session(/.*)?:匹配任意随机串后接end-session的所有子路径(含参数)

2. Traefik配置示例(YAML格式)

在中间件配置中,给正则加!前缀表示反向匹配:

middlewares:
  redirect-except-specific:
    redirectRegex:
      regex: "!^https?://[^/]+/(whatever/else|application/o/(authorize(/.*)?|[^/]+/end-session(/.*)?))$"
      replacement: "https://your-target-domain${request_uri}" # 替换为你的目标重定向地址
      permanent: true # 根据需求选择永久/临时重定向

内容的提问来源于stack exchange,提问作者Slav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:06:21