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

在XAMPP中配置PHP CMS友好URL时出现404错误求助

问题分析与解决方案

你的核心问题出在**.htaccess规则错误**、路径匹配逻辑混乱,以及PHP跳转逻辑冗余,以下是分步解决方法:

1. 修正.htaccess规则(关键)

原规则存在两个致命问题:没有正确捕获/传递参数,且路径匹配不符合你的项目结构。根据你的需求(友好URL为https://localhost/posts/[slug],映射到/ProjetoCMS/PostContainer.php?slug=[slug]),分两种场景配置:

场景1:.htaccess放在Apache根目录(即localhost对应的目录)

RewriteEngine On

# 规则1:将旧URL永久重定向到友好URL(地址栏变更)
RewriteCond %{QUERY_STRING} ^slug=([^&]+)&id=\d+$
RewriteRule ^ProjetoCMS/PostContainer\.php$ /posts/%1? [R=301,L]

# 规则2:将友好URL内部转发到实际处理文件(地址栏不变)
RewriteRule ^posts/([^/]+)/?$ /ProjetoCMS/PostContainer.php?slug=$1 [L]

场景2:.htaccess放在ProjetoCMS目录下(友好URL带ProjetoCMS前缀,如localhost/ProjetoCMS/posts/[slug])

RewriteEngine On

# 规则1:旧URL跳转
RewriteCond %{QUERY_STRING} ^slug=([^&]+)&id=\d+$
RewriteRule ^PostContainer\.php$ posts/%1? [R=301,L]

# 规则2:友好URL内部转发
RewriteRule ^posts/([^/]+)/?$ PostContainer.php?slug=$1 [L]

说明:R=301是永久重定向,利于SEO;末尾的?用于清除原URL的查询字符串;L表示终止后续规则匹配。

2. 调整PostContainer.php的业务逻辑

既然友好URL只传递slug,你需要修改代码,通过slug唯一查询文章(确保数据库中slug字段唯一),不再依赖id参数:

// 获取slug参数,处理空值情况
$slug = $_GET['slug'] ?? '';
if (empty($slug)) {
    header("HTTP/1.0 404 Not Found");
    exit;
}

// 通过slug查询数据库(示例代码)
// $db = new PDO('mysql:host=localhost;dbname=你的CMS数据库', '用户名', '密码');
// $stmt = $db->prepare("SELECT * FROM posts WHERE slug = ? LIMIT 1");
// $stmt->execute([$slug]);
// $post = $stmt->fetch(PDO::FETCH_ASSOC);

// 无匹配文章时返回404
// if (!$post) {
//     header("HTTP/1.0 404 Not Found");
//     exit;
// }

// 输出文章内容...

同时删除PHP中的跳转代码,跳转逻辑交给.htaccess处理更高效、规范。

3. 确认服务器配置

  • 确保Apache的rewrite_module已启用:检查httpd.conf中LoadModule rewrite_module modules/mod_rewrite.so未被注释,可通过phpinfo()查看模块状态。
  • 确保目标目录的AllowOverride设置为All:在httpd.conf或虚拟主机配置中,针对ProjetoCMS目录添加:
<Directory "你的ProjetoCMS目录绝对路径">
    AllowOverride All
    Require all granted
</Directory>
  • 修改配置后重启Apache服务,确保生效。

4. 测试验证

  1. 访问旧URL:https://localhost/ProjetoCMS/PostContainer.php?slug=post-numero-01-teste-01&id=1,应自动跳转到友好URL,地址栏更新。
  2. 直接访问友好URL:https://localhost/posts/post-numero-01-teste-01,应正常加载对应文章内容,无404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:13:26