Laravel 8中如何通过Handle.php的NotFoundHttpException将404重定向到首页
Laravel 8 实现404错误重定向至首页
你只需要在renderable闭包中返回重定向到首页的响应即可,同时要修正原代码中缺失的类大括号(存在语法错误)。修改后的完整代码如下:
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; class Handler extends ExceptionHandler { /** * Register the exception handling callbacks for the application. * * @return void */ public function register() { $this->renderable(function (NotFoundHttpException $e, $request) { // 重定向至首页根路径 return redirect()->to('/'); // 若首页路由有命名(比如命名为home),也可使用以下方式 // return redirect()->route('home'); }); } }
说明
- 当系统捕获到
NotFoundHttpException(即404错误)时,会直接跳转至网站首页 - 两种重定向方式二选一即可:直接指定根路径
/,或者使用已命名的路由(需确保路由配置正确)
内容的提问来源于stack exchange,提问作者Chip Siu Nhân
相关产品推荐
相关产品推荐

