1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS EC2でLaravelを配置してALB使うときの対策(ウケウリ)

1
Last updated at Posted at 2025-12-17

単にALBを有効するとどうなるか

CSSやJavascriptや画像などアセット類が読み込まれなくなり、ChromeのDevToolsのConsole上にmixed content: The Page at 'https://example.com/' was loaded over HTTPS, but reqested an insecure stylesheet(またはscript) 'http://example.com/example.css'(または'http://example.com/example.js'). This request has been blocked; the content must be served over HTTPS.ってのがゾロゾロ出てくるようになる。
mixed_content_errors.png

たぶん、こちらの記事で触れている現象と同じことが起きているのかなって察しました:
HTTPS 通信のみ許可しているALB経由で、EC2上のWordPressにアクセスしたら、表示崩れした話。 - サーバーワークスエンジニアブログ

なぜなのか

インターネット側からALBまでのアクセスはHTTPSだけど、ALBからEC2上のwebサーバーに転送されるリクエストはHTTPSではなく HTTP だから、webサーバープログラムから呼ばれてphpで動くLaravelでは「HTTPでアクセスしてきているからアセット類はHTTPでアクセスするように応答すればいいや」と通常は判断してしまうらしく、アセット類へのアクセスがHTTPを使うように指示するレスポンスを返してしまうかららしい。

対策:TrustProxiesミドルウェアを組み込む

プロジェクトソース内、bootstrap/app.php にて、こんな風に:

bootstrap/app.php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\TrustProxies;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            TrustProxies::class, // 追加
        ]);
        $middleware->trustProxies(at: '*'); // 追加
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

参考:AWSでのMixed Contentエラー対策のためTrustProxiesミドルウェアを設定する

以上、ウケウリ情報でした!

Laravel 11環境にて確認しました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?