PHP中的自定义404错误页面

时间:2014-06-16 15:18:28

标签: php .htaccess http-status-code-404

我是PHP的新手,希望你能帮我解决这个问题。 如何在PHP中创建自定义404错误页面而不去任何地方或将其重定向到其他页面。

实施例。 mysite.com/no-where

页面no-where不存在。我想在该URL上显示带有设计的404错误消息。

如何获取当前网址?我收到了一个错误。因为我想检查标题是否为404。

$url = $_SERVER['REQUEST_URI'];
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200")) {
    echo 'url exists';
} else {
    echo 'url does not exist';
}

6 个答案:

答案 0 :(得分:3)

创建.htaccess文件并在其中加入以下行:

ErrorDocument 404 /errorpageFileName.php 

这会将页面' errorpageFileName.php设置为您的错误404页面。您当然可以根据自己的喜好更改文件名。

您可以在此处详细了解它: Custom 404 error issues with Apache

答案 1 :(得分:1)

如果您使用apache作为Web服务器,则可以在网站的根目录中创建名为.htaccess的文件。这可以包含各种规则,包括错误处理,如下所示:

ErrorDocument 404 (Your site error 404 page URL)

例如:

ErrorDocument 404 http://example.domain/custom-404-page.html

答案 2 :(得分:1)

在.htaccess中添加此行

ErrorDocument 404 "Page not found."

答案 3 :(得分:1)

拥有正确的404错误页面非常重要,因为:

  • 它可以帮助您的网站/网络应用访问者在您的网站上找到正确的位置
  • 更好的SEO
  • 看起来好多了

除了这里的答案以外,我建议您针对不同的错误类型使用不同的消息。例如,在您的.htacess文件中为不同的故障类型定义错误页面:

ErrorDocument 500 /500.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html

有关custom 404 error pages的更多信息。

答案 4 :(得分:0)

使用404标题,然后需要404模板/页面。

header('HTTP/1.0 404 Not Found');
include '404.php';
exit;

您或configure Apache可以提供自定义页面。

答案 5 :(得分:0)

如果您将apache用作Web服务器和cpanel,只需单击菜单错误页面,选择404 error not found,然后使用自定义html页面编辑编辑器并保存。您将在文件夹中获得自动文件404.shtml。

如果您使用的是vps openlitespeed和Webadmin面板,则找不到错误,并填写您的自定义404 html页面。

如果您的面板是openlitespeed的Cyber​​panel面板,只需创建您的自定义404 html页面(例如:404.html),然后编辑您的vHost Conf并用行填充:

errorpage 404 {
  url                     /404.html
}

并保存