简体   繁体   English

.htaccess通过PHP显示404、403、500,错误页面

[英].htaccess show 404, 403, 500, error pages via PHP

How can I make .htaccess display errors from a PHP file? 如何使PHP文件中的.htaccess显示错误? I mean when I search a non-existing file .htaccess should show me an error page from error.php, but error.php needs a parameter with the error code. 我的意思是,当我搜索不存在的文件时,.htaccess应该会向我显示error.php的错误页面,但是error.php需要带有错误代码的参数。

NOTE: .htaccess should show the error directly on the current url without redirecting. 注意: .htaccess应该直接在当前URL上显示错误,而不进行重定向。 Can I do this or it is impossible? 我可以这样做还是不可能? Are there any other ways? 还有其他方法吗?

You're looking for ErrorDocument . 您正在寻找ErrorDocument

In your .htaccess specify the codes you want to handle, like: 在.htaccess中,指定要处理的代码,例如:

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

And in error.php, handle the error codes like: 在error.php中,处理以下错误代码:

<?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: 当您在.htacess中引用错误页面时,您所做的只是重定向:

ErrorDocument 404 /404.htm

Change that to error.php?code=404 and then pick that up in error.php using: 将其更改为error.php?code=404 ,然后使用以下命令在error.php进行选择:

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

Voila! 瞧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM