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

htaccess URL重写异常求助:带尾斜杠的URL重写错误

URL重写规则异常修复方案

需求目标

  • 将https://example.com/@example_user/(带/不带末尾斜杠)重写为https://example.com/main.php?user=example_user
  • 将https://example.com/@example_user/config/(带/不带末尾斜杠)重写为https://example.com/main.php?user=example_user&site=config

原尝试规则

RewriteEngine On

RewriteRule ^@([^/]+)/?$ main.php?user=$1 [L,QSA]

RewriteRule ^@([^/]+)/([^/]+)/?$ main.php?user=$1&site=$2 [L,QSA]

异常现象

  • https://example.com/@example_user 正常工作
  • https://example.com/@example_user/ 错误跳转至 https://example.com/@/@example_user/
  • https://example.com/@example_user/config 正常工作
  • https://example.com/@example_user/config/ 错误跳转至 https://example.com/@%251/%252

修复后的规则

RewriteEngine On

# 关闭mod_dir自动添加末尾斜杠的跳转
DirectorySlash Off

# 优先匹配带site的路径
RewriteRule ^@([^/]+)/([^/]+)/?$ main.php?user=$1&site=$2 [L,QSA,NE]

# 匹配仅含user的路径
RewriteRule ^@([^/]+)/?$ main.php?user=$1 [L,QSA,NE]

关键修复点

  1. DirectorySlash Off:禁用Apache默认的目录斜杠自动跳转,避免它干扰重写规则的执行逻辑。
  2. 规则顺序调整:把匹配更长路径(带site参数)的规则放在前面,防止短路径规则提前匹配导致长路径规则失效。
  3. 添加NE标记:禁止Apache对反向引用变量进行二次编码,解决%251这类异常编码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:30:04