Best way to handle 404 error with redirect to homepage Best way to handle 404 error with redirect to homepage apache apache

Best way to handle 404 error with redirect to homepage


Try something like this:

<?php    header("HTTP/1.0 404 Not Found");    echo '<html>            <head>                <meta http-equiv="Refresh" content="0;url=http://www.mysite.com/index.php?code=404" />            </head><body></body>          </html>';?>

I'm using a meta redirect because otherwise you get an error that headers have already been sent.

I tested this on localhost using Fiddler, and got a proper 404 response, and then was correctly redirected to a different page successfully.


Another suggestion I would advise modifying the .htaccess to handle the 404.

adding something like :

ErrorDocument 404 /404.php

to your .htaccess will handle things very nicely for you.

You can place the 404 error template anywhere you want. For example you could place all error messages in a folder called 'errors'

ErrorDocument 404 /errors/404.php

Handles things nicely and other error messages of course.


Can you add the include("index.php") onto your 404 page without the code parameter; then within your index.php include a section that will check the URL of the current page. So if the page URL contains 404.html, include the error message, otherwise show the main index as normal.