1

Is there a way or a function within a controller that tells if a 404 error was triggered? I would like everyone to redirect at the homepage instead of seeing a 404 page.

Thanks!

Loreto Gabawa Jr.
  • 1,996
  • 5
  • 21
  • 33
  • 2
    Just a side note, it's important that your missing pages really are 404 pages sending the 404 header, otherwise search engines might continue to index broken links. Almost every major site favors 404 pages over simple redirects. The benefit of this is that you can still put functionality on your 404 page to suggest, or allow the user to search for, what they were really looking for. – Lotus Notes Nov 05 '10 at 17:45

4 Answers4

8

To catch and handle 404 errors, you need to extend the ErrorHandler class and override the error404 method. To do that, create the file app/app_error.php with the following code:

class AppError extends ErrorHandler {
    function error404($params) {
        // redirect to homepage
        $this->controller->redirect('/');
    }
}

Manual

webbiedave
  • 48,414
  • 8
  • 88
  • 101
1

CakePHP v 2.x

Using AppController::appError()

Implementing this method is an alternative to implementing a custom exception handler. It’s primarily provided for backwards compatibility, and is not recommended for new applications. This controller method is called instead of the default exception rendering. It receives the thrown exception as its only argument. You should implement your error handling in that method:

Step 1 :: File : app/Controller/AppController.php

class AppController extends Controller {
    public function appError($error) {
        // custom logic goes here. Here I am redirecting to a custom page
        header("Location : /pages/notfound");
    }
}

Step 2 :: Create custom view. app/View/pages/notfound.ctp

Write custom message in this file.

Reference :

http://book.cakephp.org/2.0/en/development/exceptions.html#using-appcontroller-apperror

Community
  • 1
  • 1
Umar Sid
  • 1,317
  • 1
  • 17
  • 24
0

For CakePHP 2.x I used

// app/Lib/Error/AppExceptionRenderer.php
<?php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
    public function error400($error) { 
        return $this->controller->redirect('/');
    }

}

//app/Config/Core.php

Configure::write('debug', 0);
Configure::write('Exception', array(
        'handler' => 'ErrorHandler::handleException',
        //'renderer' => 'ExceptionRenderer',
        'renderer' => 'AppExceptionRenderer',
        'log' => true
    ));
A J
  • 3,970
  • 14
  • 38
  • 53
tsukimi
  • 1,605
  • 2
  • 21
  • 36
0

The simple way is to put this in your app/Config/core.php

Configure::write('Exception.handler', function ($error) {
    header('Location: https://www.example.com');
});

Please note that anonymous functions as callback are supported by PHP v5.3+

Leonajs
  • 341
  • 3
  • 13