CakePHP:将所有404错误重定向到主页?

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!

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

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
    ));

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+

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