LoginSignup
29
25

More than 5 years have passed since last update.

Laravel5.6のメンテナンスモードについて(許可IPを指定方法など)

Last updated at Posted at 2018-05-12

前置き

Laravelに標準でついてるメンテナンスモードですが、許可IPを指定できることを今日知りました。ホワイトリストを指定したりするために、自作 or 改修の必要があると思っていたので、目から鱗です。
どうもLaravel5.6になって実装されたものらしく、5.5では使えません。

以下の内容は公式ドキュメントにも記載されています。
https://laravel.com/docs/5.6/configuration#maintenance-mode

一方、5.5のドキュメントを見ると許可IPの指定については書いてありませんでした。
メッセージとRetry-Afterの指定は5.5でもできるみたい。
https://laravel.com/docs/5.5/configuration#maintenance-mode

使い方

通常

php artisan down

許可IP指定オプションを指定する場合

IP1つの場合

php artisan down --allow=192.168.0.0/16

IP2つの場合

php artisan down --allow=127.0.0.1 --allow=192.168.0.0/16

表示に使えるメッセージを指定する場合

php artisan down --message="テストだよ!"

※ これはデフォルトでは表示されないみたいです。表示に使えるしログの出力なんかにも使えるよ的なものみたい。

HTTPヘッダーのRetry-Afterを設定

php artisan down --retry=60

仕組み

php artisan down を実行するとstorage/framework/downというファイルができます。
このファイルを以下のミドルウェアでチェックしてます。

Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode 

で、この storage/framework/downというファイルを開いてみると以下のようなjsonになってます。


{
    "time": 1526117372,
    "message": "\u30c6\u30b9\u30c8\u4e2d\u3060\u3088!",
    "retry": 60,
    "allowed": [
        "111.111.11.1",
        "192.168.10.1"
    ]
}

CheckForMaintenanceModeクラスの中でdownファイルの中に記述されるjsonを参照しています。
CheckForMaintenanceModeクラスの方を抜粋しておきます。
(存在確認のほうはIlluminate\Foundation\ApplicationクラスのisDownForMaintenanceメソッドでやってます。こちらは普通にfile_exists関数を使って判定してるだけなので割愛します。)


public function handle($request, Closure $next)
{
    if ($this->app->isDownForMaintenance()) {
        $data = json_decode(file_get_contents($this->app->storagePath().'/framework/down'), true);

        if (isset($data['allowed']) && IpUtils::checkIp($request->ip(), (array) $data['allowed'])) {
            return $next($request);
        }

        throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
    }
}

ちなみにCheckForMaintenanceModeミドルウェアの登録はapp/Http/Kernel.phpに記述されてます。

結び

ホワイトリストの機構を自作しちゃったよぉ><
作り終わってからこのオプションに気が付いたよぉ><

29
25
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
29
25