您可以让它与中间件类一起工作.让我给你一个主意.
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
file,如下所示:
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
.因此,只需根据您的喜好调整设置即可.
云焰
我在带有通配符SSL的生产环境中使用了这段代码,代码运行正常.如果我删除&& App::environment() === 'production'
并在localhost中测试它,重定向也可以工作.因此,是否安装SSL不是问题.看起来您需要非常关注云焰层,以便重定向到Https协议.
2015年3月23日编辑
多亏了@Adam Link
的建议:这可能是由云焰传递的头文件引起的.CloudFlare可能通过HTTP访问您的服务器,并传递一个X-Forwarded-Proto头,该头声明它正在转发HTTPS请求.您需要在中间件中添加另一行,即...
$request->setTrustedProxies( [ $request->getClientIp() ] );
...要信任CloudFlare正在发送的头文件.这将停止重定向循环
编辑2016年9月27日-Laravel V5.3
只需将中间件类添加到kernel.php file
中的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
],
];
请记住,默认情况下,web
组应用于每条路由,因此您不需要在路由或控制器中显式设置web
.
编辑2018年8月23日-拉维尔v5.7.
- 要根据环境重定向请求,可以使用
App::environment() === 'production'
.之前的版本是
- 使用
\URL::forceScheme('https');
实际上不会重定向.它只是在网站呈现后与https://
建立链接.