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

Laravel 5.2 How To redirect All 404 Errors to Homepage

如何将所有 404 错误重定向到主页?我有自定义错误页面,但 google 分析引发了太多错误。

为此,您需要在 app/Exceptions/Handler.php 文件中的 render 方法中添加几行代码。

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;
        }
    }
   
        return parent::render($request, $e);      
}

对于 php 7.2 + Laravel 5.8 的我来说,它就像一个老板。 我更改了渲染方法 (app/Exceptions/Handler.php)。 因此,我们必须检查异常是否是 HTTP 异常,因为我们正在调用 getStatusCode() 方法,该方法仅在 HTTP 异常中可用。 如果状态码是404,我们可能return一个视图(例如:errors.404)或者重定向到某处或路由(home)。

app/Exceptions/Handler.php

public function render($request, Exception $exception)
    {

        if($this->isHttpException($exception)) {
            switch ($exception->getStatusCode()) {
                // not found
                case 404:
                    return redirect()->route('home');
                    break;

                // internal error
                case 500:
                    return \Response::view('errors.500', [], 500);
                    break;

                default:
                    return $this->renderHttpException($exception);
                    break;
            }
        } else {
            return parent::render($request, $exception);
        }

    }

测试: 添加 abort(500);在您的控制器流中的某处查看 page/route。我使用了 500,但您可以使用错误代码之一:Abort(404)...

abort(500);

我们可以选择提供回复:

abort(500, 'What you want to message');

我将此添加到 routes/web。php 以将 404 页面重定向到主页

Route::any('{query}', function() { return redirect('/'); })->where('query', '.*');

Laravel 8+ 现在使用 Register 方法检查异常。 您可以使用以下代码来捕获和重定向 404 错误。

app/Exceptions/Handler.php

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (NotFoundHttpException $e, $request) {
            return redirect()->route('home');
        });
    }

您可以在 Laravel 文档中找到详细信息 here

设置Laravel(任意版本)自定义404(任意错误页面)页面

步骤 1 转到/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/views/这个位置

步骤 2 在这里你会找到所有的错误页面现在编辑你想编辑的页面这里我是changning 404页面所以我只编辑404.blade.php现在我们只需要输入一行代码就像

步骤 3 echo "location.href='/404'";

步骤 4 删除这个文件的旧代码或者你可以注释掉这个文件的旧代码。

步骤 5 在 404 页面上保存并重新加载您的网站。

(这里我创建了404路由来处理404页面)

了解更多 https://devsecit.com Kanai Shil - DEV SEC IT Pvt。有限公司