40
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?