症状:

当触发错误(如 404 Not Found 或 500 Internal Server Error)时,自定义错误页面未按预期显示,而是显示了默认的 Apache 错误页面或空白页面。

故障排除步骤:

  1. 检查 ErrorDocument 指令的配置
    确保 Apache 配置文件中正确设置了 ErrorDocument 指令。运行以下命令查找配置:

    bash grep ErrorDocument /etc/httpd/conf/httpd.conf

    或(对于 Debian/Ubuntu 系统):

    bash grep ErrorDocument /etc/apache2/apache2.conf

    如果未找到配置,可能需要手动添加。例如:

    apache ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html

  2. 确认自定义错误页面的存在和权限
    确保自定义错误页面文件存在于指定路径,并且 Apache 用户有权限访问这些文件。例如:

    bash ls -l /var/www/html/errors/404.html

    如果文件不存在,需要创建它。同时,确保文件权限正确:

    bash sudo chmod 644 /var/www/html/errors/404.html sudo chown apache:apache /var/www/html/errors/404.html

  3. 检查错误页面的路径是否正确
    确保 ErrorDocument 指令中指定的路径是相对于 DocumentRoot 的相对路径。例如,如果 DocumentRoot 是 /var/www/html,则 /errors/404.html 应位于 /var/www/html/errors/404.html。

  4. 检查虚拟主机配置(如果适用)
    如果使用了虚拟主机,ErrorDocument 指令可能需要在虚拟主机配置中设置。例如:

    apache <VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html </VirtualHost>

  5. 重启 Apache
    在修改配置或调整文件权限后,重启 Apache 服务以使更改生效:

    bash systemctl restart httpd

    或:

    bash systemctl restart apache2

  6. 验证自定义错误页面是否生效
    在浏览器中访问一个不存在的页面(如 http://example.com/nonexistent-page),确认是否显示自定义的 404 错误页面。同样,可以通过触发其他错误(如 500 错误)来测试其他自定义页面。

  7. 检查 .htaccess 文件(如果适用)
    如果启用了 .htaccess 文件,确保没有冲突的 ErrorDocument 指令。例如:

    apache ErrorDocument 404 /errors/404.html

    确保 .htaccess 文件的权限正确,并且 AllowOverride 指令允许覆盖配置:

    apache <Directory "/var/www/html"> AllowOverride All </Directory>

  8. 查看 Apache 错误日志
    如果自定义错误页面仍然未显示,查看 Apache 的错误日志以获取更多线索:

    bash tail -f /var/log/httpd/error_log

    或:

    bash tail -f /var/log/apache2/error.log

    日志中可能会显示与错误页面相关的错误信息。

通过以上步骤,可以逐步排查并解决自定义错误页面未显示的问题,确保在触发错误时能够正确显示自定义的错误页面。