【问题标题】:CakePHP redirect with status code 404CakePHP 重定向,状态码为 404
【发布时间】:2012-07-01 09:38:58
【问题描述】:

对于 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 代码?

【问题讨论】:

    标签: php cakephp redirect http-status-code-404 cakephp-2.0


    【解决方案1】:

    CakePHP 3

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

        throw new NotFoundException();
        

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

        还有更多内置异常here

        如果您有兴趣制作自定义错误页面,请参阅this post

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-28
          • 1970-01-01
          • 1970-01-01
          • 2022-07-07
          • 1970-01-01
          • 2019-03-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多