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?

More than 3 years have passed since last update.

CloudFrontでContent-Typeを強制的に書き換える

Posted at

背景

とある静的なWebサイトを、S3+CloudFrontという王道構成で運営しています。

CyberDuckというとても便利なFTPソフトがあり、そこからS3にもファイルをアップロードしたのですが、なぜか、全部のファイルが Content-Type: binary/octet-stream になってしまいました。

スクリーンショット 2021-11-07 17.33.25.png

一つ一つ変更したり、CLIで変換してもいいのですが、面倒なのでLambda@Edgeで変換します。
Origin Response で下記のLambdaFunctionを実行するように設定しました。

index.js
'use strict'
exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response
    const headers = response.headers
    const request = event.Records[0].cf.request;

    if (request.uri.match(/.jpg$|.jpeg$/i)) {
        console.log("jpeg matched")
        headers['content-type'] = [{
            "key": "Content-Type",
            "value": "image/jpeg",
        }];
    }
    if (request.uri.match(/.htm$|.html$/i)) {
        console.log("html matched")
        headers['content-type'] = [{
            "key": "Content-Type",
            "value": "text/html",
        }];
    }
    if (request.uri.match(/.css$/i)) {
        console.log("css matched")
        headers['content-type'] = [{
            "key": "Content-Type",
            "value": "text/css",
        }];
    }
    if (request.uri.match(/.js$/i)) {
        console.log("js matched")
        headers['content-type'] = [{
            "key": "Content-Type",
            "value": "text/javascript",
        }];
    }

    callback(null, response)
}

すべてに疲れたのでelseすらつけていない、汎用化すらしていない横着スクリプトの共有です。

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?