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

PHP与.htaccess URL重写问题:友好URL跳转异常排查

问题解决:URL友好化后results页面跳转至home的问题

核心问题分析

  1. .htaccess规则错误:第二个RewriteRule的正则表达式不符合需求,仅匹配results后跟随数字的路径(如results123),无法匹配你需要的/results?show=first&tid=xxx格式。
  2. PHP路径获取逻辑错误:使用basename($_SERVER['REQUEST_URI'])会把URL中的查询字符串(?show=first&tid=xxx)也包含进去,导致$file的值变成results?show=first&tid=xxx,无法匹配switch中的case "results",最终进入default加载首页。
  3. 文件路径拼写错误:PHP代码中controller/serach-result.php的serach是拼写错误,应为search,否则匹配成功后也会找不到目标文件。

修正后的.htaccess文件

RewriteEngine on
RewriteBase /

# 匹配静态页面路径
RewriteRule ^(home|about-us|contact-us|login)$ index.php?a=$1 [L]

# 匹配results页面,保留查询字符串
RewriteRule ^results$ index.php [QSA,L]

# 处理空路径(首页)
RewriteRule ^$ index.php?a=home [L]

修正后的PHP代码

// 解析请求URI,单独提取路径部分(去除查询字符串)
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = protect(trim(basename($uri)));

switch($file) {
    case "home" : include("sources/home_page.php"); break;
    case "about-us" : include("sources/about.php"); break;
    case "login" : include("sources/login.php"); break;
    case "contact-us" : include("sources/contact.php"); break;
    case "logout" : include("controller/logout.php"); break;
    case "results" : include("controller/search-result.php"); break; // 修正拼写错误
    default: include("sources/home.php");
}

关键说明

  • .htaccess中的QSA标记用于保留原URL的查询字符串,确保show和tid参数能正常传递到index.php。
  • 使用parse_url单独提取路径部分,避免了查询字符串干扰basename的结果,确保$file能准确匹配switch的case项。
  • 修正拼写错误后,才能正常加载结果页面的控制器文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:22:40