1

如何使 PHP 文件中的 .htaccess 显示错误?我的意思是当我搜索一个不存在的文件时,.htaccess 应该会显示一个来自 error.php 的错误页面,但是 error.php 需要一个带有错误代码的参数。

注意: .htaccess 应该直接在当前 url 上显示错误,而不需要重定向。我可以这样做还是不可能?还有其他方法吗?

4

3 回答 3

8

你正在寻找ErrorDocument.

在您的 .htaccess 中指定您要处理的代码,例如:

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

在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');
    }
?>
于 2014-09-16T13:13:20.180 回答
1
//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
于 2014-09-16T13:03:18.173 回答
0

当您在 .htacess 中引用错误页面时,您所做的只是重定向:

ErrorDocument 404 /404.htm

将其更改为error.php?code=404然后error.php使用:

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

瞧!

于 2014-09-16T13:07:42.037 回答