Laravel 5.2如何将所有404错误重定向到主页

Bug*_*njo 8 redirect http-status-code-404 http-status-code-301 laravel laravel-5.2

如何将所有404错误重定向到主页?我有自定义错误页面,但谷歌分析投掷了太多错误.

sha*_*lpk 20

为此,您需要renderapp/Exceptions/Handler.php文件中添加几行代码.

public function render($request, Exception $e)
{   
    if($this->isHttpException($e))
    {
        switch (intval($e->getStatusCode())) {
            // not found
            case 404:
                return redirect()->route('home');
                break;
            // internal error
            case 500:
                return \Response::view('custom.500',array(),500);
                break;

            default:
                return $this->renderHttpException($e);
                break;
        }
    }
    else
    {
        return parent::render($request, $e);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 1

请考虑文档中给出的答案: https://laravel.com/docs/10.x/routing#fallback-routes

例如,在您的网络文件中:

Route::fallback(function () {
    return redirect()->route('index');
});
Run Code Online (Sandbox Code Playgroud)