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

如何配置Caddy不对含特定字符串的User-Agent执行重定向?

解决Caddy指定User-Agent跳过HTTPS重定向的问题

你可以直接通过改写表达式实现取反,Caddy的表达式支持not运算符,直接对匹配条件取反即可,不需要依赖负向前瞻或者复杂的正则技巧。

下面给你两种可行的配置方案:

方案一:用header_contains精准匹配指定字符串

这种方式不需要正则,更直观,适合匹配固定字符串(包括带空格的):

http://www.example.com {
  # 定义匹配器:匹配User-Agent不包含任何指定字符串的请求
  @notExcluded not header_contains(User-Agent, "foo") and not header_contains(User-Agent, "bar") and not header_contains(User-Agent, "b a z")
  # 仅对符合@notExcluded的请求执行重定向
  redir @notExcluded https://{host}{uri}
}

方案二:用正则一次性匹配所有排除项

如果需要匹配的字符串较多,用正则分组更简洁:

http://www.example.com {
  # 定义匹配器:匹配User-Agent不包含foo/bar/b a z中任意一项的请求
  @notExcluded not header_regexp(User-Agent, "(foo|bar|b a z)")
  # 仅对符合@notExcluded的请求执行重定向
  redir @notExcluded https://{host}{uri}
}

补充说明

你之前尝试的多header_regexp组合表达式,只要用not包裹整个或条件即可正常使用,比如:

not (header_regexp('User-Agent', '(foo)') || header_regexp('User-Agent', '(bar)') || header_regexp('User-Agent', '(b a z)'))

不过用单个正则分组把所有排除项整合起来,写法会更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 19:11:01