CakePHP: Redirecting all 404 errors to the homepage?

后端 未结 4 1814
遥遥无期
遥遥无期 2021-01-07 11:17

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.

相关标签:
4条回答
  • 2021-01-07 11:47

    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

    0 讨论(0)
  • 2021-01-07 11:52

    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+

    0 讨论(0)
  • 2021-01-07 11:56

    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
        ));
    
    0 讨论(0)
  • 2021-01-07 12:06

    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

    0 讨论(0)
提交回复
热议问题