【问题标题】:Cloudfront redirect for S3 subdirectoriesS3 子目录的 Cloudfront 重定向
【发布时间】:2021-12-06 03:05:05
【问题描述】:

我有一个 S3 存储桶,其中包含多个目录 /experiment1experiment2 等。在每个目录中都有一个包含相关文件(index.html、js 包)的静态应用程序。这些应用中的每一个都有自己的应用内 SPA 路由器来处理路由。

对于 index.html,访问这些应用程序的路由相对简单,转到https://blahblah.com/experiment1/ 按预期工作,呈现应用程序。问题是当它比目录根更深时。例如,转到https://blahblah.com/experiment1/about 将给出 404,因为 S3 上自然不存在该文件。 过去,当 S3 存储桶中只有一个“应用程序”时,将 404 原始响应重定向到 Cloudfront 中的 /index.html 是有效的。在这种情况下,这将不起作用,因为我需要动态重定向到/experiment*/index.html。以下是我尝试过但未能成功运行的 Lambda@Edge 配置。

感谢任何帮助

exports.handler = (event, context, callback) => {
    'use strict';
    const response = event.Records[0].cf.response;
    // grabs the experiment1 part of /experiment1/about
    const firstPath = response.uri.split('/')[1];
    
    if (response.status == 404) {
        
        //Response Status Code and Description
        response.status = 200;
        response.statusDescription = 'OK';
        
        response.body = '';
        
        //Set the Redirect Location
        response.headers['location'] = [{ key: 'Location', value: `/${firstPath}/index.html` }];
    }
    callback(null, response);
};

这个配置只是给了我一个空白页,状态为 200

【问题讨论】:

    标签: javascript amazon-web-services amazon-s3 amazon-cloudfront


    【解决方案1】:

    使用 HTTP 状态码 302 表示临时重定向,而不是使用状态码 200 表示成功。

    response.status = 302;
    response.statusDescription = 'Found';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2014-03-04
      • 2017-05-14
      • 2020-07-15
      • 2016-12-08
      相关资源
      最近更新 更多