php CakePHP 重定向状态码为 404

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11268849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:08:39  来源:igfitidea点击:

CakePHP redirect with status code 404

phpcakephpredirecthttp-status-code-404cakephp-2.0

提问by trante

For CakePHP errors I know that there exists CakeError and AppError solutions. But I need to make a redirection within controller.

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

In AppControllerthere exists:

AppController中存在:

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

But this doesn't create a 404 status code. It creates a 302 code. I changed code to this:

但这不会创建 404 状态代码。它创建了一个 302 代码。我把代码改成这样:

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

But the result is same.

但结果是一样的。

I added this, it didn't work also deprecated:

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

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

How can I send a 404 code within controller redirect ?

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

回答by swiecki

If you want to return a 404 error, use the built in CakeError support for it:

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

throw new NotFoundException();

You can throw this exception from your controller and it should generate a 404 response.

您可以从控制器抛出此异常,它应该会生成 404 响应。

There are more built-in exceptions here.

还有更多的内置异常这里

If you are interested in making a custom error page, then see this post.

如果您有兴趣制作自定义错误页面,请参阅此帖子

Otherwise, I don't think it is possible to return a 404 header code and still redirect. Http specifies redirect status codes to be in the 300s, and this is the convention CakePHP follows.

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

回答by Giuppe

For some reason using redirect() will change the status code to 3xx. If you want to execute another action and still return 404, you can do as follows:

出于某种原因,使用 redirect() 会将状态代码更改为 3xx。如果你想执行另一个动作,仍然返回404,你可以这样做:

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

This will execute Mycontroller::error(404) without redirect.

这将在没有重定向的情况下执行 Mycontroller::error(404)。

回答by Szymon Fabianski

CakePHP 3

蛋糕PHP 3

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