ZTefter
ZTefter

Reputation: 199

Best way to handle 404 error with redirect to homepage

I've searched, read a lot, but still couldn't find a way, to achieve my goal. Now I even think it is impossible. Is it?

I want 404 errors to handled properly so I have ErrorDocument 404 /404.php in the .htaccess file, and I want to send out the right header to search engines header("HTTP/1.1 404 Not Found") to forget that page, also I want to redirect my visitor to /index.php?code=404 so I can inform him about that what he was looking for is not available, but still keep him on the site.

Now it seems everything is fine, until I want to redirect the user: then the server sends out a 302 message, which overwrites my previous 404 header, so while I can send the user to the desired place, I still can't tell the searchbots that the address is wrong.

If I add a include("index.php?code=404") after the header line it just won't work, the server says that file does not exist.

What should I do?

Upvotes: 3

Views: 21733

Answers (3)

Pogrindis
Pogrindis

Reputation: 8101

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.

Upvotes: 5

Alfo
Alfo

Reputation: 4819

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.

Upvotes: 7

anotherdave
anotherdave

Reputation: 6754

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.

Upvotes: 0

Related Questions