您可以使它与中间件类工作。让我给你一个想法。
namespace MyApp\Http\Middleware;
use Closure;
class HttpsProtocol {
public function handle($request, Closure $next)
{
if (!$request->secure() && env('APP_ENV') === 'prod') {
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)
>如果你的环境等于prod。因此,只需根据您的喜好调整设置。
Cloudflare
我在生产环境中使用这个代码与WildCard SSL,代码正常工作。如果我删除&& env(‘APP_ENV’)===’prod’并在localhost中测试,重定向也可以工作。所以,是否安装了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
只需要在kernel.php文件中将中间件类添加到web组中:
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// here
\MyApp\Http\Middleware\HttpsProtocol::class
],
];
Remember that web group is applied to every route by default, so you do not need to set web explicitly in routes nor controllers.