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

CloudFrontでメンテナンス(503)のレスポンスを返すAPIを設定する(CORS対応版)

Posted at

CloudFrontの関数でメンテナンス(503)を返却するプログラムです。
あとはこれをビューワーリクエストに設定すればOKです。

以下手順です。

手順1:CloudFront関数を作成する。

  1. CloudFrontコンソールを開き、左ペインから「関数」をクリックし、「関数を作成」をクリック。
     関数名:maintenance
     Runtime:cloudfront-js-2.0
    として、「関数を作成」をクリック。

  2. 「関数コード」に以下をコピペして、「変更を保存」をクリック

  3. 「発行」タブをクリック後、「関数を発行」をクリック ※忘れがちなので注意

maintenance
function handler(event) {
    // メンテナンスモード時はここを手動で動かす
    const isMaintenance = false <===== メンテナンス時は true に設定する
    const maintenanceStart = "2025年1月1日 00:00"
    const maintenanceEnd = "2025年1月3日 23:59"
    // 手動で動かすのここまで

    const request = event.request

    if (!isMaintenance) {
        // メンテナンスモード中以外はそのままリクエストをオリジンに通す
        return request
    }

    const response = {
        statusCode: 503,
        statusDescription: 'Service Unavailable',
        headers: {
            'content-type': { value: 'application/json' },
            'access-control-allow-credentials': { value: 'true' },
        },
        body: JSON.stringify({
            "maintenanceStart": maintenanceStart,
            "maintenanceEnd": maintenanceEnd,
            "message": "システムメンテナンス中です。"
        })
    }

    // メンテナンスモード中もオリジンへのアクセスを許可するIP群
    const allowedIPs = [
       '1.2.3.4',
    ]

    // 許可オリジン フロントエンドのオリジン
    const allowedOrigins = [
        'https://hogehoge-frontend.com' <===== フロント側のURLを指定する(CORS対策)
    ]

    const clientIP = event.viewer.ip
    const origin = request.headers.origin ? request.headers.origin.value : ''

    if (allowedIPs.includes(clientIP) || request.method === 'OPTIONS') {
        // OPTIONS か 許可IP の場合は通す
        return request
    } else if (allowedOrigins.includes(origin)) {
        // レスポンスヘッダーに許可されたオリジンを設定することでCORS違反を避ける
        response.headers['access-control-allow-origin'] = { value: origin }
    }

    return response
}

Step2:ビューアーリクエストの設定

  1. 左ペイン「ディストリビューション」をクリックし、該当のディストリビューションのリンクをクリック
  2. 「ビヘイビア」タブをクリックし、該当のビヘイビアをチェックして「編集」クリック
  3. ページ下部にある「ビューアーリクエスト」から
     関数タイプ:CloudFront Functions
     関数 ARN/名前:maintenance
    を選択して「変更を保存」クリック

これで、HTTP503が返却され、メンテナンスになる。
あとは、フロントエンド側で HTTP503が返却されたら、それなりの画面を作ればOK。

以上

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