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

Apache环境下PHP路由仅部分路径返回404页面问题排查

问题解决:PHP路由自定义404未触发,返回Apache默认404

核心原因

你的Apache未配置正确的URL重写规则,导致除根路径/之外的请求(比如/auth、/404)会被Apache直接查找对应物理文件/目录,找不到就返回默认404,根本没进入PHP路由的处理逻辑。

解决方案

1. 完善.htaccess重写规则

在public目录的.htaccess中添加完整规则,将所有请求转发到index.php:

RewriteEngine On
# 排除真实存在的文件和目录
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 将所有请求重写到index.php
RewriteRule ^(.*)$ index.php [QSA,L]
  • QSA:保留请求的查询参数
  • L:标记为最后一条规则,不再执行后续重写

2. 启用Apache rewrite模块

如果未启用rewrite模块,执行以下命令:

sudo a2enmod rewrite
sudo systemctl restart apache2

3. 确保.htaccess生效

检查site.conf中的目录配置,将AllowOverride设为All:

<Directory /var/www/site/public>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

修改后重启Apache:

sudo systemctl restart apache2

4. 修正拼写不一致问题

项目目录中视图文件夹名为accuellie,但路由代码里写的是accueille,建议统一拼写避免后续问题:

'/' => function () {
    include(VIEWS_PATH . DS . 'accuellie' . DS . 'accuellie.php');
},

5. 优化路由逻辑(可选)

简化路由判断逻辑,直接检查路由是否存在:

function run()
{
    $uri = explode('?', $_SERVER['REQUEST_URI'], 2);
    $routes = [
        '/' => function () {
            include(VIEWS_PATH . DS . 'accuellie' . DS . 'accuellie.php');
        },
        '/auth' => function () {
            include(VIEWS_PATH . DS . 'auth' . DS . 'login.php');
        },
    ];
    $path = $uri[0];
    
    if (isset($routes[$path])) {
        $routes[$path]();
    } else {
        include(VIEWS_PATH . DS . '404' . DS . '404.html');
        http_response_code(404); // 发送标准404状态码
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:47:31