php - 自定义 apache 500 错误 PHP 页面

标签 php apache custom-error-pages

好吧,我想我要在这里失去理智了......

一直在尝试和测试,但似乎无法加载自定义 HTTP 500 错误页面。 Chrome 一直为我提供默认的“此页面无效,HTTP 错误 500”错误页面。

我采取的步骤:

  • 创建了 500.php 文件,它将显示我需要的自定义页面
  • 使用以下行更改 .htaccess 文件
  • 在服务器上创建了一个文件,该文件将加载一个不存在的类,从而导致 500 错误。
  • Access_log 显示请求和 500 状态

  • 访问日志

    :1 - - [10/Aug/2018:20:51:39 +0200] "GET / HTTP/1.1" 500 -



    错误日志

    [Fri Aug 10 20:51:39.156104 2018] [php7:error] [pid 11608] [client ::1:65263] PHP Fatal error: Uncaught Error: Class 'tests' not found in /private/var/www/development/public_html/index.php:7\nStack trace:\n#0 {main}\n thrown in /private/var/www/development/public_html/index.php on line 7



    .htaccess 行
    ErrorDocument 400 /404.php
    ErrorDocument 403 /403.php
    ErrorDocument 404 /404.php
    ErrorDocument 405 /405.php
    ErrorDocument 408 /408.php
    ErrorDocument 500 /500.php
    ErrorDocument 502 /502.php
    ErrorDocument 504 /504.php
    

    Apache 2.4+
    PHP 7+

    我在这里没有看到这个问题,特别是因为上面的 404 版本运行完美。 500.php 只包含 echo '500';

    我在这里错过了一些 Apache 设置吗?是不是因为是本地的...

    最佳答案

    你的评论基本上是正确的。许多 500 错误不会以 .htaccess 的方式到达 apache。将能够重定向到错误文档。

    有两种方法可以为 5xx 错误发布自定义模板。您使用哪一个将取决于错误是什么。如果错误是“Catchable ”,您只需要将函数包装在 try/catch 中堵塞。像这样的东西:

    try{
        someUndefinedFunction();
    } catch (Throwable $exception) { //Use Throwable to catch both errors and exceptions
        header('HTTP/1.1 500 Internal Server Error'); //Tell the browser this is a 500 error
        echo $e->getMessage();
    }
    

    请注意,在此示例中,必须手动设置 500 错误 header 。这是因为错误在 try{} 内从浏览器的角度来看,阻止服务器实际上并没有出错。

    如果 500 错误是由无法捕获的内容引起的,那么您需要注册自定义关闭功能。这在 php7+ 中不太常见,但仍然可能是必要的,具体取决于您在做什么。完成的方法是包含这样的内容:
    function handle_fatal_error() {
        $error = error_get_last();
        if (is_array($error)) {
            $errorCode = $error['type'] ?? 0;
            $errorMsg = $error['message'] ?? '';
            $file = $error['file'] ?? '';
            $line = $error['line'] ?? null;
    
            if ($errorCode > 0) {
                handle_error($errorCode, $errorMessage, $file, $line);
            }
        }
    }
    function handle_error($code, $msg, $file, $line) {
        echo $code . ': '. $msg . 'in ' . $file . 'on line ' . $line;
    }
    set_error_handler("handle_error");
      register_shutdown_function('handle_fatal_error');
    

    关于php - 自定义 apache 500 错误 PHP 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792814/

    相关文章:

    php - MYSQL 查询到 Codeigniter 查询

    php - 对可变位宽二进制 block 中的十进制值进行编码/解码

    apache - 尝试使用 certbox 获取 SSL 证书,但命令 sudo certbot --apache 在 ec2 实例上失败

    asp.net-mvc - .net mvc 404自定义错误页面有时只能工作

    iis-7.5 - IIS 7.5 自定义 404 错误页面不适用于 Web 根索引/默认

    php - 递归下拉菜单未在 Bootstrap Codeigniter 上正确显示

    php - 如何解码json ajax响应

    linux - iptables、apache、Linux Mint (Ubuntu),从端口 80 转发到 1080,没有可用的监听套接字,正在关闭

    php - 如何让新版本的 openssl 显示在我的 phpinfo 中

    iis - 当服务(例如 ColdFusion)关闭时,IIS 7.5 中的自定义错误页面