错误文档和 .htaccess

ErrorDocument and .htaccess

我正在 php 中编写 CMS,因此我希望允许用户在不破坏应用程序的情况下更改根文件夹的名称。我目前正在尝试使用特定于目录的 .htaccess 文件为自定义错误页面设置一些文件处理。我的文件树相对如下:

MAMP >
|   htdocs >
|   |   cms > 
|   |   |   .htaccess
|   |   |   index.php
|   |   |   cms_files >
|   |   |   |   info.json
|   |   |   |   . . . 
|   |   |   |   error_pages >
|   |   |   |   |   errors.php
|   |   |   |   |

而我标记为 'cms' 的文件夹应该可以修改。

所以我的问题是,在我的 .htaccess 文件中,我使用 ErrorDocument 404 /cms/cms_files/error_pages/errors.php 处理该文档中的错误代码,它工作正常。但是,就像我说的,我需要能够在不破坏 ErrorDocument 文件路径的情况下更改 'cms' 的名称,并且从我所有的在线搜索中,我似乎找不到任何可以让我设置亲戚的东西.htaccess 中的路径,相对于它当前所在的目录。

基本上我希望能够做类似

的事情
ErrorDocument 404 CURRENT_DIRECTORY/cms_files/error_pages/errors.php

避免对根文件夹进行硬编码。

有什么简单的方法吗?或者可能是仅使用 php 而不是 .htaccess 的替代选项?提前致谢!

p.s。 .htaccess 文件和 error_pages 文件夹必须保留在各自的目录中,以防用户想要创建 cms 的多个安装,所有特定于安装的信息必须包含在其中(在本例中 'cms') 文件夹。这是关于为什么文件夹必须能够在不破坏的情况下更改名称的另一个警告。

根据 Apache 文档,似乎根本不支持相对路径:(https://httpd.apache.org/docs/2.4/custom-error.html)

The syntax of the ErrorDocument directive is:

ErrorDocument <3-digit-code> <action>

where the action will be treated as:

  1. A local URL to redirect to (if the action begins with a "/").

  2. An external URL to redirect to (if the action is a valid URL).

  3. Text to be displayed (if none of the above). The text must be wrapped in quotes (") if it consists of more than one word.

但是,如果您进一步阅读文档,听起来您可以将其他数据传递给重定向的 URL:

Redirecting to another URL can be useful, but only if some information can be passed which can then be used to explain or log the error condition more clearly.

To achieve this, when the error redirect is sent, additional environment variables will be set, which will be generated from the headers provided to the original request by prepending 'REDIRECT_' onto the original header name. This provides the error document the context of the original request.

阅读所有可用重定向信息的文档。您可能会在那里找到有用的东西。

考虑到额外的重定向信息,也许您将所有 404 重定向到某种控制器,该控制器通过 PHP 将用户重定向到正确的 404 页面。

您可以为 ErrorDocument 使用单个 PHP 文件,就像这样

ErrorDocument 404 /404.php

/404.php 放在服务器文档根目录中,因为它将用于所有 404 处理。

404.php文件将读取请求的路径,检查路径是否为子目录,如果是,您可以使用 includeredirect 以显示某些内容或将用户重定向到子目录中的 404.php 页面。

<?php
// Get the path that was requested
$pathComponents = explode('/',$_SERVER['REQUEST_URI']);

// The first element on the path is the directory of interest
$baseDirRequested = $pathComponents[0];

// If the directory exists, either include or redirect to that 404 file
if (is_dir($baseDirRequested)) {
        // Include
        include $baseDirRequested.'/404.php';
        // -- or --
        // Redirect
        header('Location: '.$baseDirRequested.'/404.php');
        exit;
} else {
        echo 'You are really lost';
}

在子目录404.php

<?php 
// 404 for search engines 
header("HTTP/1.1 404 Not Found"); 
?>
<!-- HTML for people -->

使用 include 的好处是你可以提供任何你想要的内容,这可能是一个更流畅的用户体验。您可能更喜欢使用重定向将用户路由回子目录逻辑。

我还没有测试过这个,它可能需要一些调整。