.htaccess show 404, 403, 500, error pages via PHP

梦想的初衷 提交于 2019-11-29 17:38:06

You're looking for ErrorDocument.

In your .htaccess specify the codes you want to handle, like:

ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

And in error.php, handle the error codes like:

<?php
    $code = $_SERVER['REDIRECT_STATUS'];
    $codes = array(
        403 => 'Forbidden',
        404 => 'Not Found',
        500 => 'Internal Server Error'
    );
    $source_url = 'http'.((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    if (array_key_exists($code, $codes) && is_numeric($code)) {
        die("Error $code: {$codes[$code]}");
    } else {
        die('Unknown error');
    }
?>
//Custom 403 errors
ErrorDocument 403 your-path/403.php

//Custom 404 errors
ErrorDocument 404 your-path/404.php

//Custom 500 errors
ErrorDocument 500 your-path/500.php

When you reference an error page in .htacess, all your doing is a redirect:

ErrorDocument 404 /404.htm

Change that to error.php?code=404 and then pick that up in error.php using:

if($_GET['code'] == '404') {
    include('404.php');
}

Voila!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!