S3子目录的Cloudfront重定向



我有一个S3桶,其中有多个目录/experiment1,experiment2等。在每个目录中都有一个静态应用程序,其中包含相关文件(index.html、js bundle)。这些应用中的每一个都有自己的应用内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

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

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

最新更新