LoginSignup
39
24

More than 3 years have passed since last update.

LaravelでURLをHTTPS化させるメモ (Heroku)

Last updated at Posted at 2020-11-22

LaravelでURLを強制httpsかさせる方法で、よくある対策ではうまくいかなかったのでメモ。

APP_ENVをproductionに

Herokuの場合、heroku config:setで環境変数を設定。

heroku config:set APP_ENV=production

AppServiceProviderのboot()にforceSchemeを

AppServiceProviderのboot()に下記を追加

AppServiceProvider.php
public function boot()
{
    if (\App::environment(['production'])) {
        \URL::forceScheme('https');
    }
}

HttpをHttpsにリダイレクト

Middlewareでhttpによるアクセスをhttpsにリダイレクトする
ForceHttpsという名前のmiddlewareを作成
php artisan make:middleware ForceHttps
handle()のところに下記を追加

ForceHttps.php
public function handle($request, Closure $next)
{
  if (\App::environment(['production']) && $_SERVER["HTTP_X_FORWARDED_PROTO"] != 'https') {
    return redirect()->secure($request->getRequestUri());
  }
  return $next($request);
}

Kernel.phpにForceHttpsを追加

Kernel.phpに先ほど作成したForceHttps.php middlewareを追加

Kernel.php
protected $middleware = [
  \App\Http\Middleware\ForceHttps::class, // 追加
];

image.png

39
24
1

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
39
24