php 重定向到https,php – Laravel 5 – 重定向到HTTPS
您可以使它與中間件類工作。讓我給你一個想法。
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.
總結
以上是生活随笔為你收集整理的php 重定向到https,php – Laravel 5 – 重定向到HTTPS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多个php一个机器,如何利用docker
- 下一篇: php prettyprinter,gd