【问题标题】:Laravel 5.2 How To redirect All 404 Errors to HomepageLaravel 5.2 如何将所有 404 错误重定向到主页
【发布时间】:2016-06-13 13:35:38
【问题描述】:
如何将所有 404 错误重定向到主页?我有自定义错误页面,但谷歌分析抛出了太多错误。
【问题讨论】:
标签:
laravel
redirect
http-status-code-404
http-status-code-301
laravel-5.2
【解决方案1】:
为此,您需要在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);
}
【解决方案2】:
对于使用 php 7.2 + Laravel 5.8 的我来说,它就像一个老板。
我更改了渲染方法(app/Exceptions/Handler.php)。
因此,我们必须检查异常是否为 HTTP 异常,因为我们正在调用 getStatusCode() 方法,该方法仅在 HTTP 异常中可用。
如果状态码是 404,我们可能会返回一个视图(例如:errors.404)或重定向到某个地方或路由(家)。
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);在您的控制器流程中的某处查看页面/路由。我用的是 500,但你可以使用错误代码之一:Abort(404)...
abort(500);
我们可以选择提供回复:
abort(500, 'What you want to message');
【解决方案3】:
我将这个添加到 routes/web.php 以将 404 页面重定向到主页
Route::any('{query}', function() { return redirect('/'); })->where('query', '.*');