大网数据广告活动
网站运营与故障问答

PHP Undefined index: REDIRECT_STATUS - error 404

· 52CE 我爱测

Custom 404 page in PHP using .htaccess file. If page dosen't exist redirect to error.php. I don't know why but it doesn't work. Notice: Undefined index: REDIRECT_STATUS on line 2 <?php $error = $_SERVER["REDIRECT_STATUS"]; $ettor…

问题原文

原帖链接 · Mantykora 7 · CC BY-SA 4.0

Custom 404 page in PHP using .htaccess file. If page dosen't exist redirect to error.php. I don't know why but it doesn't work. Notice: Undefined index: REDIRECT_STATUS on line 2

<?php 
$error = $_SERVER["REDIRECT_STATUS"];
$ettor_title = '';
$error_message = '';
    if($error == 404) {
        $ettor_title = '404 Page Not Found';
        $error_message = 'The document/file requested was not found on this server';
    }
    ?>
    
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Error</title>
    </head>
    
    <body>
        <h1><?php echo $ettor_title; ?></h1>
        <h5><?php echo $error_message; ?></h5>
    </body>
    </html>

.htaccess

ErrorDocument 404 https://doamin.com/error.php

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

ErrorDocument 404 https://doamin.com/error.php

You need to use a root-relative URL-path, not an absolute URL in the ErrorDocument directive. If you specify an absolute URL then it will trigger a 302 redirect to the error document (and a 200 OK response when the error document is served) and consequently, any information about the request that caused the error (such as REDIRECT_STATUS and REDIRECT_URL etc.) is lost - which is what's happening here.

A root-relative URL-path results in an internal subrequest and a 404 response from Apache. For example:

ErrorDocument 404 /error.php

Reference:

Aside:

$error = $_SERVER["REDIRECT_STATUS"];

However, you should always test that the variable exists before using it. If the error document is requested directly (which is essentially what's happening above) then REDIRECT_STATUS is not set. For example:

$error = $_SERVER["REDIRECT_STATUS"] ?? null;

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2021-01-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。