Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

他のフレームワークでは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

crowdworks
21世紀の新しいワークスタイルを提供する日本最大級のクラウドソーシング「クラウドワークス」のエンジニアチームです!
https://crowdworks.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした