CakePHP redirect with status code 404 CakePHP redirect with status code 404 php php

CakePHP redirect with status code 404


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

throw new NotFoundException();

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

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.


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:

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

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


CakePHP 3

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