我想使用以下方法将数据库中不再存在的页面重定向到自定义404页面:
ob_start();
....
if ( !$found ):
header( "Location: /404.php", true, 404 );
exit();
endif;
但这实际上并没有重定向,只是显示了一个空页面(因为在任何输出到浏览器之前都会调用exit())。
我也尝试过以下方法:
if ( !$found ):
header( "HTTP/1.1 404 Not Found" );
exit();
endif;
在我的.htaccess文件中有一个"ErrorDocument 404/404.php",但这也只是显示了一个空页面。
如果我这样做:
if ( !$found ):
header( "HTTP/1.1 404 Not Found" );
header( "Location: /404.php" );
exit();
endif;
它确实重定向,但有一个302标头。
如有任何帮助,我们将不胜感激。
我知道这是一个老问题,但我发现它很方便:
php将状态头设置为404,并添加一个刷新到正确的页面,就像2秒后一样。
header('HTTP/1.1 404 Not Found');
header("Refresh:0; url=search.php");
然后,在重定向到fx搜索页面之前,404页面会显示几秒钟。
在我的案例中,Symfony2有一个异常侦听器:
$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');
时间(2)可以是0.2,如果你希望非常短的时间。
我已经尝试并确保检查error_log文件,正确的方法是发送404个标题,然后在下一行包含错误页面。
<?php
header('HTTP/1.1 404 Not Found');
include 'search.php'; // or 404.php whatever you want...
exit();
?>
最后,您必须对基于文本的浏览器使用exit()。
您不能有一个带有Location的头404:
如果您想重定向
meta refresh
我认为您的问题是因为您正在启动的输出缓冲,或者因为您无法使用404重定向。第一个代码示例显示输出缓冲区启动但退出,而不是清理输出缓冲区并停止输出缓冲。
将第一个示例更改为:
if (!$found) {
ob_end_clean();
header('Location: /404.php');
exit();
}
也许没有重定向?
if ( !$found ):
include('../404.php');
exit();
endif;