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]
关键修复点
DirectorySlash Off:禁用Apache默认的目录斜杠自动跳转,避免它干扰重写规则的执行逻辑。- 规则顺序调整:把匹配更长路径(带site参数)的规则放在前面,防止短路径规则提前匹配导致长路径规则失效。
- 添加
NE标记:禁止Apache对反向引用变量进行二次编码,解决%251这类异常编码问题。
内容的提问来源于stack exchange,提问作者Ylich
相关产品推荐
相关产品推荐

