php larvel https,Laravel 5-重定向到HTTPS

小编典典

您可以使其与Middleware类一起使用。让我给你个主意。

namespace MyApp\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\App;

class HttpsProtocol {

public function handle($request, Closure $next)

{

if (!$request->secure() && App::environment() === 'production') {

return redirect()->secure($request->getRequestUri());

}

return $next($request);

}

}

然后,将此中间件应用于每个请求,在Kernel.php文件中添加设置规则,如下所示:

protected $middleware = [

'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',

'Illuminate\Cookie\Middleware\EncryptCookies',

'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',

'Illuminate\Session\Middleware\StartSession',

'Illuminate\View\Middleware\ShareErrorsFromSession',

// appending custom middleware

'MyApp\Http\Middleware\HttpsProtocol'

];

在上述示例中,如果满足以下条件,则中间件会将每个请求重定向到https:

当前请求没有安全协议(http)

如果您的环境等于production。因此,只需根据您的喜好调整设置。

云耀斑

我在具有WildCard SSL的生产环境中使用此代码,并且该代码可以正常工作。如果我&& App::environment() ===

'production'在本地主机中删除并对其进行测试,则重定向也有效。因此,是否安装SSL并不是问题。看来您需要非常注意Cloudflare层才能重定向到Https协议。

编辑23/03/2015

感谢@Adam Link的建议:很可能是Cloudflare传递的标头引起的。CloudFlare可能通过HTTP命中了您的服务器,并传递了X-

Forwarded-Proto标头,该标头声明其正在转发HTTPS请求。您需要在中间件中添加另一行,说明…

$request->setTrustedProxies( [ $request->getClientIp() ] );

…信任CloudFlare发送的标头。这将停止重定向循环

编辑27/09/2016-Laravel v5.3

只需要将中间件类添加到以下web组中kernel.php file:

protected $middlewareGroups = [

'web' => [

\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,

\Illuminate\Session\Middleware\StartSession::class,

\Illuminate\View\Middleware\ShareErrorsFromSession::class,

// here

\MyApp\Http\Middleware\HttpsProtocol::class

],

];

请记住,web默认情况下该组将应用于每个路由,因此您无需web在路由或控制器中进行显式设置。

编辑23/08/2018-Laravel v5.7

根据环境可以重定向请求App::environment() === 'production'。对于以前的版本是 env('APP_ENV') === 'production'。

使用\URL::forceScheme('https');实际上不会重定向。https://网站建成后,它仅与之建立链接。

2020-05-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值