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

Caddy 2(FrankenPHP)配置中,是否有更优的URL末尾斜杠去除方法?

去除URL末尾斜杠并保留查询参数的Caddy最优配置

需求

实现URL末尾斜杠的去除,同时保留已有的查询参数,示例如下:

  • /support/ → /support
  • /support/?id=123 → /support?id=123

现有方案(双匹配器)

当前使用两个独立匹配器分别处理无查询参数和有查询参数的场景:

# 处理无查询参数的情况
@trailing-slash-path-no-query {
    method GET
    path_regexp trailingSlash ^(.+)/$
    query ""
}
redir @trailing-slash-path-no-query {re.trailingSlash.1} 301

# 处理带查询参数的情况
@trailing-slash-path-with-query {
    method GET
    path_regexp trailingSlash ^(.+)/$
    not query ""
}
redir @trailing-slash-path-with-query {re.trailingSlash.1}?{query} 301

之所以用两个匹配器,是因为Caddy的{query}变量不包含?前缀,直接用单一匹配器重定向会导致无查询参数的URL被重定向到/support?这种不符合需求的格式。

单匹配器优化方案

可以利用Caddy的**表达式(expression)**功能,通过单个匹配器实现动态拼接重定向目标,避免冗余配置:

@trailing-slash {
    method GET
    path_regexp trailingSlash ^(.+)/$
}
redir @trailing-slash expression `{re.trailingSlash.1} + (query != "" ? "?" + query : "")` 301

方案说明

  • 表达式中通过query != ""判断是否存在查询参数:
    • 当有查询参数时,拼接?{query}到路径后
    • 当无查询参数时,直接返回去除斜杠后的路径
  • 整个逻辑通过单个匹配器完成,配置更简洁,同时避免了生成带多余?的URL问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 05:12:34