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

自定义PHP MVC架构中Apache重写规则与header()函数冲突求助

问题分析

重定向失败的核心是Apache重写规则形成了无限循环:

  1. 当public/index.php执行跳转指令时,浏览器发起对/templates/errors/erreur-technique.php的请求
  2. 根目录.htaccess会把所有非/public/开头的请求重写到/public/$1,导致/templates/...被转为/public/templates/...
  3. public目录的.htaccess检查请求URI是否以/templates/errors/开头,但此时URI是/public/templates/errors/...,不满足排除条件,于是被再次重写到public/index.php
  4. index.php再次触发跳转,循环往复,最终浏览器判定重定向无效
解决方案

1. 修改根目录.htaccess,排除templates路径的重写

在根目录的重写规则里加入对/templates/的排除,让这类请求直接访问真实文件,不经过public目录:

RewriteEngine On
# 排除public和templates目录的请求,不进行重写
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{REQUEST_URI} !^/templates/
RewriteRule ^(.*)$ /public/$1 [L]

2. 优化public/index.php的跳转路径

去掉硬编码的域名,使用站点根目录的绝对路径,提升配置灵活性:

// Composer autoload file
// with bad filename to throw an error 
$sVendorDir = $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload123.php';

if (file_exists($sVendorDir)) {
   require_once $sVendorDir;
} else {
   $sLogMsg = "Echec du chargement du fichier '$sVendorDir' (".__FILE__.":".__LINE__.")";
   error_log($sLogMsg);
   // 使用站点根目录绝对路径跳转,无需硬编码域名
   header("Location: /templates/errors/erreur-technique.php");
   exit;
}

3. 可选:确认templates目录权限

确保Apache服务器对templates目录及其中的PHP文件有读取权限,避免出现403访问错误

验证逻辑

修改完成后,当index.php触发跳转时:

  • /templates/errors/erreur-technique.php的请求会被根目录.htaccess排除重写,直接访问真实文件
  • 不会进入public目录的重写规则,彻底打破循环,跳转可正常生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:00:55