如何使用 .htaccess 文件制作自定义错误页面

How to make a custom error page using .htaccess file

我正在尝试为每个错误生成一个自定义错误页面

这是我的目录

.htaccess
error_pages:
           error_400.html
           error_401.html
           error_404.html

你很接近。首先,如果您还没有这样做,您需要初始化您的 .htaccess 文档。

RewriteEngine On

接下来,您需要定义错误并告诉 .htaccess 使用哪个文件来处理该错误:

ErrorDocument 400 /error_pages/error_400.html
ErrorDocument 401 /error_pages/error_401.html
ErrorDocument 404 /error_pages/error_404.html

希望这对您有所帮助。

您已标记您的问题 php,但在您的示例中使用了 .html?如果您使用 PHP,那么您不需要为每个 HTTP 状态单独的错误文档。您可以使用相同的 PHP 错误文档并检查 REDIRECT_STATUS(即 $_SERVER['REDIRECT_STATUS'] 超全局)以确定触发错误文档的错误状态。

因此,您的 .htaccess 文件将包含:

ErrorDocument 400 /error_pages/error_handler.php
ErrorDocument 401 /error_pages/error_handler.php
ErrorDocument 404 /error_pages/error_handler.php

参考: