1

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

1 Answer 1

1
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;
1
  • 1
    root-relative URL-path that was my problem. Thank you very much for your help. Jan 19, 2021 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.