自定义PHP MVC架构中Apache重写规则与header()函数冲突求助
问题分析
重定向失败的核心是Apache重写规则形成了无限循环:
- 当
public/index.php执行跳转指令时,浏览器发起对/templates/errors/erreur-technique.php的请求 - 根目录
.htaccess会把所有非/public/开头的请求重写到/public/$1,导致/templates/...被转为/public/templates/... public目录的.htaccess检查请求URI是否以/templates/errors/开头,但此时URI是/public/templates/errors/...,不满足排除条件,于是被再次重写到public/index.phpindex.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
相关产品推荐
相关产品推荐

