【问题标题】:Custom 404 Error Page in PHPPHP中的自定义404错误页面
【发布时间】:2014-08-06 11:20:21
【问题描述】:

我是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';
}

【问题讨论】:

  • 创建一个404.php 页面或404.htm 文件,使用任何你想要的样式,然后在.htaccess 中做ErrorDocument 404 /404.php,不是吗?还是认为这太“Old Skool”了?
  • 不,我不想将用户重定向到其他页面。我想在他/她当前正在浏览的网址上准确显示错误消息。
  • 好的,那就看看韦恩的回答吧。
  • ErrorDocument 404 /404.php 不会更改您的原始网址。它将保留在浏览器中的mysite.com/no-where
  • 当我尝试它时出现错误The requested URL /no-where was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

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


【解决方案1】:

创建一个 .htaccess 文件并将以下行放入其中:

ErrorDocument 404 /errorpageFileName.php 

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

您可以在这里阅读更深入的内容: Custom 404 error issues with Apache

【讨论】:

    【解决方案2】:

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

    • 它可以帮助您的网站/网络应用访问者引导您网站中的正确位置
    • 更好的搜索引擎优化
    • 只是看起来更好

    除了此处的答案外,我建议您针对不同的错误类型提供不同的消息。例如,在您的 .htacess 文件中定义不同故障类型的错误页面:

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

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

    【讨论】:

      【解决方案3】:

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

      ErrorDocument 404 (Your site error 404 page URL)
      

      例如:

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

      【讨论】:

        【解决方案4】:

        在 .htaccess 中添加这一行

        ErrorDocument 404 "Page not found."
        

        【讨论】:

          【解决方案5】:

          使用 404 标头,然后需要您的 404 模板/页面。

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

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

          【讨论】:

            【解决方案6】:

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

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

            如果您的面板是 openlitespeed 的网络面板,只需创建您的自定义 404 html 页面(例如:404.html),然后编辑您的 vHost Conf 并填写以下行:

            errorpage 404 {
              url                     /404.html
            }
            

            然后保存

            【讨论】:

              猜你喜欢
              • 2016-04-25
              • 2013-09-16
              • 2012-03-26
              • 2015-03-18
              • 2011-08-05
              • 1970-01-01
              • 1970-01-01
              • 2017-08-07
              相关资源
              最近更新 更多