要将AWS CloudFront中index.html中的CSS和JS引用重写为index_files/style.css,您可以使用CloudFront的Lambda@Edge功能来实现。
以下是一个示例Lambda函数代码,该函数可以在CloudFront的Origin Request事件期间重写index.html中的CSS和JS引用:
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
// 获取请求的路径
const path = request.uri;
// 检查请求是否为index.html
if (path.endsWith('index.html')) {
// 获取请求的主机名
const host = request.headers.host[0].value;
// 替换CSS引用
const rewrittenIndexHtml = request.body.text
.replace('css/style.css', 'index_files/style.css');
// 更新请求的内容
request.body.text = rewrittenIndexHtml;
// 更新响应头部,设置Content-Length
const response = event.Records[0].cf.response;
response.headers['content-length'] = [{key: 'Content-Length', value: String(Buffer.byteLength(rewrittenIndexHtml, 'utf8'))}];
}
callback(null, request);
};
请注意,上述示例代码假设您的Lambda函数位于us-east-1区域。如果您的函数位于其他区域,请相应地更改函数的ARN。
在AWS Lambda控制台中,您将需要创建一个新的Lambda函数,并将上述代码粘贴到函数代码编辑器中。然后,您可以将该函数与CloudFront的Origin Request事件关联起来。
在CloudFront控制台中,选择您的分布式,然后选择“Behaviors”选项卡。找到您希望在其中重写引用的行为,并单击“Edit”。在“Lambda Function Associations”部分,选择“Origin Request”事件,并选择您的Lambda函数。
完成上述步骤后,当请求的路径以index.html结尾时,Lambda函数将在CloudFront的Origin Request事件期间被触发,并重写index.html中的CSS和JS引用为index_files/style.css。
请注意,在将Lambda函数与CloudFront关联后,您可能需要等待一段时间才能看到效果生效,因为CloudFront可能需要一些时间来将更改部署到所有边缘节点。