I'd like to use the following to redirect pages that are no longer present in the database to the custom 404 page:
ob_start();
....
if ( !$found ):
header( "Location: /404.php", true, 404 );
exit();
endif;
But this actually does not redirect, but just shows an empty page (because of the exit() call before any output to the browser).
I've also tried the following:
if ( !$found ):
header( "HTTP/1.1 404 Not Found" );
exit();
endif;
With a 'ErrorDocument 404 /404.php' in my .htaccess file, but this also just shows an empty page.
And if I do this:
if ( !$found ):
header( "HTTP/1.1 404 Not Found" );
header( "Location: /404.php" );
exit();
endif;
It does redirect, but with a 302 header.
Any help would be greatly appreciated.
The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error. Like following example, there should not be any output of even a space before the headers are sent.
php file, you can create one as a simple HTML file with a . php extension and then upload it to your site's theme directory. Any time a 404 error occurs, WordPress will serve up this 404. php page to the user.
PHP Header Location In order for your PHP redirect to be successful, the header() function must execute — and before any output is sent. This is why your code must appear above the <! DOCTYPE html> or <html> tags in your index. php file.
I've tried and make sure to check error_log file that is correct way is send 404 headers and then include error page to next line.
<?php
header('HTTP/1.1 404 Not Found');
include 'search.php'; // or 404.php whatever you want...
exit();
?>
Finally you have to use exit() for text based browsers.
I know it's a old issue but I just found it handy:
php set status header to 404 and add a refresh to correct page, like a 2 seconds after.
header('HTTP/1.1 404 Not Found');
header("Refresh:0; url=search.php");
Then you have the 404 page showing up a few second before redirecting to fx search page.
In my case, Symfony2, with a exception listener:
$request = $event->getRequest();
$hostname = $request->getSchemeAndHttpHost();
$response->setStatusCode(404);
$response->setContent('<html>404, page not found</html>');
$response->headers->set('Refresh', '2;url='.$hostname.'/#!/404');
time ( 2) can be 0.2 if you wish very short time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With