Skip to main content

手順 5. Lambda@Edge で index.html 表示

何のためにやる作業か

  • AWS では 普通の Web サーバにはある //index.html に読み替える動作にならない
  • S3 に配置しただけだとたしか設定で出来る
  • CloudFront にはそれがないらしく
  • Lambda@Edge を使う ( Lambda とは別物? )
    • 通常の AWS Lambda とは異なり、CloudFront のリクエスト処理時に分散エッジロケーションで実行される関数
    • CloudFront のリクエスト/レスポンスのタイミングで挿入できる

Lambda@Edge に関数?を作成

  • TODO: なんかのコピペかつ、手を加えてしまったので合っているのかよくわからないので、見直す
js
'use strict';
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event that is sent to Lambda@Edge
var request = event.Records[0].cf.request;

// Extract the URI from the request
var olduri = request.uri;

// Match any '/' that occurs at the end of a URI. Replace it with a default index
//var newuri = olduri.replace(/\/$/, '\/index.html');
var newuri = olduri.replace(/\/([^\/\.]+)\/?$/, '/$1/index.html');

// Log the URI as received by CloudFront and the new URI to be used to fetch from origin
console.log("Old URI: " + olduri);
console.log("New URI: " + newuri);

// Replace the received URI with the URI that includes the index page
request.uri = newuri;

// Return to CloudFront
return callback(null, request);
};

CloudFront から呼び出すタイミングを指定?

  • CloudFront > Behaviors

    • Default の 1行のみあるはずなので、選択 > Edit
  • Lambda Function Associations 欄に下記を指定

項目
CloudFront EventOrigin Request
Lambda Function ARNLambda の関数の画面から [ARNをコピー] で取得したもの (arn:aws:lambda:...) に バージョン番号(:1) を追記したもの (・・・?)

課題

  • TODO: subdir/は置換してくれるけどsubdirは置換されない。とか、うまく行ってないところがあるのでもうちょい調べたい