CakePHP 404 redirect

For CakePHP errors, I know that there are CakeError and AppError solutions. But I need to do a redirect in the controller.

In AppController there is:

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

But this does not create a 404 status code. It creates a 302 code. I changed the code to this:

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

But the result is the same.

I added this; it did not work and is deprecated:

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

How can I send 404 code to the controller redirection?

+6
source share
3 answers

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

 throw new NotFoundException(); 

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

There are more built-in exceptions here .

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

Otherwise, I don’t think you can return the 404 header code and redirect it. Http indicates redirection status codes in the 300s , and this is an agreement accepted by CakePHP.

+17
source

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

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

This will cause Mycontroller :: error (404) to run without redirection.

+3
source

CakePHP 3

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

Source: https://habr.com/ru/post/919356/


All Articles