.htaccess中URL查询参数转路径重定向失效问题排查
问题分析与修复方案
你的规则不生效主要有三个原因:
- 现有规则针对
test.php和/test路径编写,但你实际需要处理的是page.php和/i路径,匹配目标完全不符 - 规则顺序错误:
public目录的内部重写规则会优先将所有非public开头的请求转到public/xxx,导致/i/xxx被错误转发到public/i/xxx(而非目标文件public/page.php) - 未针对实际请求路径调整正则匹配逻辑
以下是修正后的完整.htaccess代码:
# Disable directory browsing Options -Indexes # Rewrite URLs RewriteEngine On RewriteBase /clarity/ # Redirect to https and www RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^clarity\.rf\.gd [NC] RewriteRule ^(.*)$ https://www.clarity.rf.gd/$1 [L,R=301] # 1. 外部跳转:将 /i?l=xxx 重定向为 /i/xxx RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /i\?l=([^\&\ ]+) [NC] RewriteRule ^i$ /i/%1? [L,R=301] # 2. 内部重写:将 /i/xxx 映射到 public/page.php?l=xxx RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^i/(.*)$ public/page.php?l=$1 [L,QSA] # Redirect to public folder RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC] RewriteRule ^ %1 [L,NE,R=301] RewriteRule ^((?!public/).*)$ public/$1 [L,NC] # Remove .html RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^([^\.]+)$ $1.html [NC,L] # Remove .php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([^\.]+)$ $1.php [NC,L]
关键修改说明
- 替换原有的
test相关规则,改为针对/i路径和page.php的匹配规则 - 将跳转和重写规则移至
public目录重写规则之前,避免请求被错误转发 - 添加
QSA标记,确保如果URL带有其他查询参数也能正常传递 - 精准匹配
THE_REQUEST中的/i?l=xxx格式,避免误匹配其他路径
测试注意事项:
- 清空浏览器缓存(301重定向会被浏览器缓存)
- 访问
https://www.clarity.rf.gd/i?l=my-event,应自动跳转到https://www.clarity.rf.gd/i/my-event且页面正常加载 - 直接访问
https://www.clarity.rf.gd/i/my-event,需确认能正确映射到public/page.php?l=my-event
内容的提问来源于stack exchange,提问作者J. O'Ceallacháin
相关产品推荐
相关产品推荐

