CakePHP 重定向,状态代码为 404


CakePHP redirect with status code 404

对于 CakePHP 错误,我知道存在 CakeError 和 AppError 解决方案。但是我需要在控制器中进行重定向。

AppController中存在:

function afterFilter() {
    if ($this->response->statusCode() == '404')
    {
        $this->redirect(array(
            'controller' => 'mycontroller',
            'action' => 'error', 404),404
        );
    }
}

但这不会创建 404 状态代码。它创建一个 302 代码。我将代码更改为:

$this->redirect('/mycontroller/error/404', 404);

但结果是一样的。

我添加了这个,它不起作用也已弃用:

$this->header('http/1.0 404 not found');

如何在控制器重定向中发送 404 代码?

如果要返回 404 错误,请使用内置的 CakeError 支持:

throw new NotFoundException();

您可以从控制器引发此异常,它应该生成 404 响应。

这里还有更多内置异常。

如果您有兴趣创建自定义错误页面,请参阅这篇文章。

否则,我认为不可能返回 404 标头代码并仍然重定向。Http 指定重定向状态代码为 300,这是 CakePHP 遵循的约定。

出于某种原因,使用 redirect() 会将状态代码更改为 3xx。如果要执行另一个操作但仍返回 404,可以执行以下操作:

$this->controller->response->statusCode(404);
$this->controller->render('/mycontroller/error/404');
$this->controller->response->send();

这将执行 Mycontroller::error(404) 而不重定向。

蛋糕PHP 3

use Cake'Network'Exception'NotFoundException;
...
throw new NotFoundException(__('Article not found'));