Skip to content

Instantly share code, notes, and snippets.

@nariyu
Created November 2, 2021 14:01
Show Gist options
  • Save nariyu/fe72a65736f843c34b11e4818eec2ff3 to your computer and use it in GitHub Desktop.
Save nariyu/fe72a65736f843c34b11e4818eec2ff3 to your computer and use it in GitHub Desktop.
ディレクトリアクセスに index.html を補完する Lambda@Edge 関数
'use strict';
exports.handler = (event, context, callback) => {
// リクエスト
const request = event.Records[0].cf.request;
// `/moja` から `/moja/` にリダイレクト
if (request.uri.match(/\/([^\.\/]+)$/)) {
const url = request.uri.replace(/(\/[^\.\/]+\/?)$/, '$1/').replace(/\/\/+/g, '/');
const response = {
status: '302',
statusDescription: 'Found',
body: 'Location: ' + url,
headers: {
'location': [{key: 'Location', value: url}]
},
};
return callback(null, response);
}
// スラッシュで終わっていたら index.html を補完
request.uri = request.uri.replace(/(\/[^\.\/]+\/?)$/, '$1/index.html').replace(/\/\/+/g, '/');
// リクエストを続ける
callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment