首页 > 其他分享 >【前端】AWS CloudFront + S3 配置访问时自动跳转到index.html

【前端】AWS CloudFront + S3 配置访问时自动跳转到index.html

时间:2022-08-29 15:48:44浏览次数:89  
标签:function index S3 request uri html 跳转

需求:我把前端代码上传到S3了,CloudFront 的 Distribution ID E1U1XXXX,它的 Alternate domain name 是 test.link

则我访问首页需要输入 test.link/frontend/view/index.html

如何改成访问 test.link 就自动跳转到 index.html?

  1. 在AWS的 CloudFront 主页左侧菜单找到 Functions

  2. 点击 Create function

image

  1. 输入以下代码

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;
}
  1. Test 通过后,点击 Publish 的 Publish Function 按钮
  2. Publish 下方的 Associated distributions 里添加应用此 function 的 distribution

image

即可愉快地访问首页啦~
LalaLuna & SciAds

标签:function,index,S3,request,uri,html,跳转
From: https://www.cnblogs.com/lalaluna/p/16636096.html

相关文章