【问题标题】:Laravel 5: Use 301 instead of 302Laravel 5:使用 301 而不是 302
【发布时间】:2017-01-28 05:37:28
【问题描述】:

如何更新我的 Laravel 应用以在重定向时使用 301 错误代码,而不是 Laravel 当前使用的默认 302

例如在我的routes.php中我使用redirect()函数设置错误码301

return redirect('URL_GOES_HERE/', 301);

但我在应用程序中发生了许多重定向。有没有办法简单地将所有重定向中的默认 302 更改为 301

【问题讨论】:

  • 您不想使用自定义错误视图?
  • @NinoArmani 不,我需要使用 301 错误代码重定向到其他 URL。

标签: php laravel redirect laravel-5


【解决方案1】:

重定向器将 302 定义为默认值 这里是关于Redirector.php 的完整参考资料 你可以覆盖它

【讨论】:

    【解决方案2】:

    在这里检查错误响应代码 app/Exceptions/Handler.php

    public function render($request, Exception $e)
    {
      // If response code 404 then do this
      if($e->getStatusCode() == 404)
      {  
        return redirect()->to('/error'); 
      }
    
      // If response code 301
      if($e->getStatusCode() == 301)
      {  
        return redirect()->to('/do'); 
      }
    
      if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
      }
    
      if ($e instanceof \Illuminate\Session\TokenMismatchException) {
        return redirect('/')->with('message', 'Sorry, your session seems to have expired. Please login again.');
      }
    
      return parent::render($request, $e);
    }
    

    【讨论】:

    • 但是$e->getStatusCode() == 301不检查响应码是否为301?我的默认是302。我需要做的是将默认的302 更改为301。必须使用301 重定向的每个 URL 都有自己的 URL,应该将其重定向到该 URL。
    猜你喜欢
    • 2011-11-20
    • 2019-04-12
    • 2015-03-15
    • 2012-02-04
    • 2021-10-19
    • 1970-01-01
    • 2013-11-26
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多