需求:我把前端代码上传到S3了,CloudFront 的 Distribution ID E1U1XXXX,它的 Alternate domain name 是 test.link
则我访问首页需要输入 test.link/frontend/view/index.html
如何改成访问 test.link 就自动跳转到 index.html?
-
在AWS的 CloudFront 主页左侧菜单找到 Functions
-
点击 Create function
- 输入以下代码
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/example-function-add-index.html
The following example function appends index.html to requests that don’t include a file name or extension in the URL. This function can be useful for single page applications or statically generated websites that are hosted in an Amazon S3 bucket.
以下示例函数会将 index.html 附加到不在 URL 中包含文件名或扩展名的请求中。此函数对于托管在 Amazon S3 存储桶中的单页应用程序或静态生成的网站非常有用
function handler(event) {
var request = event.request;
var uri = request.uri;
// Check whether the URI is missing a file name.
if (uri.endsWith('/')) {
request.uri += 'index.html';
}
// Check whether the URI is missing a file extension.
else if (!uri.includes('.')) {
request.uri += '/index.html';
}
return request;
}
- Test 通过后,点击 Publish 的 Publish Function 按钮
- 在 Publish 下方的 Associated distributions 里添加应用此 function 的 distribution
即可愉快地访问首页啦~
LalaLuna & SciAds