我正在处理我的第一个 Laravel 5 项目,但不确定在何处或如何放置逻辑以在我的应用程序上强制使用 HTTPS。这里的关键是有许多指向应用程序的域,并且只有三分之二的使用 SSL(第三个是后备域,说来话长)。所以我想在我的应用程序逻辑而不是 .htaccess 中处理这个问题。
在 Laravel 4.2 中,我使用此代码完成了重定向,该代码位于 filters.php
:
App::before(function($request)
{
if( ! Request::secure())
{
return Redirect::secure(Request::path());
}
});
我在想中间件是应该实现这样的东西的地方,但我不能完全弄清楚使用它。
谢谢!
更新
如果您像我一样使用 Cloudflare,这可以通过在控制面板中添加新的页面规则来完成。
最佳答案
您可以使其与中间件类一起使用。让我给你一个想法。
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:
- 当前请求未附带安全协议(protocol) (http)
- 如果你的环境等于
production
。因此,只需根据您的喜好调整设置即可。
Cloudflare
我在带有 WildCard SSL 的生产环境中使用此代码,并且代码可以正常工作。如果我删除 && App::environment() === 'production'
并在 localhost 中测试它,重定向也有效。所以,有没有安装 SSL 都不是问题。看起来您需要非常注意您的 Cloudflare 层才能重定向到 Https 协议(protocol)。
2015 年 3 月 23 日编辑
感谢@Adam Link
的建议:很可能是Cloudflare传递的headers造成的。 CloudFlare 可能通过 HTTP 访问您的服务器并传递一个 X-Forwarded-Proto header ,该 header 声明它正在转发 HTTPS 请求。您需要在中间件中添加另一行,说明...
$request->setTrustedProxies( [ $request->getClientIp() ] );
...信任 CloudFlare 发送的 header 。这将停止重定向循环
编辑 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 setweb
explicitly in routes nor controllers.
编辑 23/08/2018 - Laravel v5.7
- 要根据环境重定向请求,您可以使用
App::environment() === 'production'
。对于以前的版本是env('APP_ENV') === 'production'
. - 使用
\URL::forceScheme('https');
实际上不会重定向。它只是在网站呈现后使用https://
建立链接。
关于php - Laravel 5 - 重定向到 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28402726/