You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:45:32