Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

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

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