LoginSignup
54
46

More than 5 years have passed since last update.

Laravel5.3でSSL通信を強制する

Last updated at Posted at 2016-11-04

他のフレームワークではBefore Filterで実装するが、Laravelはmiddlewareで実装する。

$ php artisan make:middleware HttpsProtocol

本番とステージング環境でSSL通信を強制する。

<?php

namespace App\Http\Middleware;

use Closure;

class HttpsProtocol
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if (!$request->secure() && config('app.env') === 'production' || config('app.env') === 'staging') {
          return redirect()->secure($request->getRequestUri());
      }

      return $next($request);
    }
}

Kernelに登録

protected $middleware = [
  \App\Http\Middleware\HttpsProtocol::class,
];

ELBだとリダイレクトしまくる問題

ELBを噛ませていると、ELB(Port:443)→EC2(Port:80)のため、$request->secure()が効かなくなってしまう。EC2も443にしてしまう手もあるが、それができない場合は$_SERVER[“HTTP_X_FORWARDED_PROTO”]httpsであるかをチェックすればいいらしい。

if (config('app.env') === 'production' || config('app.env') === 'staging') {
  if ($_SERVER["HTTP_X_FORWARDED_PROTO"] != 'https') {
    return redirect()->secure($request->getRequestUri());
  }
}

続いてApp\Providers\AppServiceProviderのboot()に以下を追加
※5.4の場合はforceSchemaではなくforceSchemeにする必要がある
http://qiita.com/sawadashota/items/79b74592b7d9800868f8

if (config('app.env') === 'production' || config('app.env') === 'staging') {
  \URL::forceSchema('https');
}

※ productionとstagingはELBが必ず噛んでいる想定です。ELBを噛んでいない場合は$_SERVER["HTTP_X_FORWARDED_PROTO"]の値が存在しないので、エラーになります。

参考

http://stackoverflow.com/questions/28402726/laravel-5-redirect-to-https
https://cloudpack.media/525

54
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
46