您可以使其与中间件类一起使用。让我给你一个主意。
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
。因此,只需根据您的喜好调整设置即可。
云耀
我在带有通配符 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
明确在路由或控制器中。
编辑 2018 年 8 月 23 日 - Laravel v5.7
- 根据您可以使用的环境重定向请求
App::environment() === 'production'
。对于以前的版本是env('APP_ENV') === 'production'
.
- Using
\URL::forceScheme('https');
实际上并没有重定向。它只是建立链接https://
一旦网站呈现。