LoginSignup
0
1

More than 5 years have passed since last update.

Platform毎にレスポンスが違う時のCloudFrontを効率よくキャッシュHITさせる方法

Last updated at Posted at 2018-01-30

要件

今回のPlatform毎にレスポンスが違うというのは、iPhone、Android、(PC)毎にアプリケーションサーバが違うレスポンス返す場合を想定する。

問題点

アプリケーションサーバ側でUAを判定して、レスポンスを生成しているため
CloudFrontで用意されている下記のフラグだけでは判定が難しい。

CloudFront-Is-Desktop-Viewer
CloudFront-Is-Mobile-Viewer
CloudFront-Is-SmartTV-Viewer
CloudFront-Is-Tablet-Viewer

デバイスタイプに基づいてオブジェクトをキャッシュするように CloudFront を設定する

結論

1. Lambda@Edgeを使ってUAを書き換える


'use strict';
exports.handler = (event, context, callback) => {

    // Get request and request headers
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    if (headers['User-Agent']) {
        headers['User-Agent'] = headers['User-Agent'][0].match(/(Android|iPhone)/)? RegExp.$1: 'Other';
    }
    callback(null, request);
}

2. CloudFrontの Whitelist HeadersUser-Agent を指定

image.png
警告が出るが無視。参考

まとめ

警告にもあるが、UAをそのままキャッシュするとUA毎のキャッシュになってしまいキャッシュのHIT効率が落ちるため、UAを簡略化させて効率良くCloudfrontを活用できる。
別のカスタムヘッダーではなく、UAに詰め直したのはアプリーケーションサーバ側のコードを変更させたくなかったため。

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