【问题标题】:Cloudfront with s3. redirect {url}/index.html to {url}/Cloudfront 与 s3。将 {url}/index.html 重定向到 {url}/
【发布时间】:2018-11-16 23:28:46
【问题描述】:
我正在使用 Amazon S3 为来自 Amazon CloudFront 的 HTTP 请求提供服务以存储文件。 S3 存储桶设置为启用网站托管。索引文档是index.html。
当我在 Google 上搜索时,我会看到这两个网址:
这两个网址都提供相同的内容。
我如何设置它以使{url}/index.html 执行代码301 永久移动 到{url}/?
【问题讨论】:
标签:
amazon-web-services
amazon-s3
amazon-cloudfront
【解决方案1】:
两个选项,复杂程度不同:
规范网址
使用<link> 标签告诉 Google 给定文档的规范 URL 是什么:
<link rel="canonical" href="https://example.com/">
使用 Lambda@Edge 重定向
您可以使用部署到 CloudFront 边缘服务器的简单 Lambda 函数。关注this tutorial,你想要的函数体(Node.js 8.10)是:
exports.handler = (event, context, callback) => {
const { request } = event.Records[0].cf;
const isIndex = request.uri.endsWith('/index.html');
if (isIndex) {
const withoutIndex = request.uri.replace(/\/index\.html$/, '');
callback(null, redirect(withoutIndex));
} else
callback(null, request);
};
function redirect(url) {
return {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
location: [{
key: 'Location',
value: url
}]
}
};
}