如何使用同一S3存储桶与CloudFront分发运行两个单页应用?
同一S3存储桶+CloudFront部署两个单页应用的路径映射配置方案
前置条件
- 已完成S3存储桶静态网站托管配置,桶根目录存在
index.html,subdirectory/子目录下也有独立的index.html(对应第二个单页应用) - 已创建指向该S3存储桶的CloudFront分发
核心配置步骤
CloudFront默认行为无法实现“存在的资源直接返回,不存在则跳转对应目录index.html”的逻辑,需要借助Lambda@Edge实现动态路径重写。
1. 创建Lambda@Edge函数(必须在us-east-1区域创建)
该函数仅在S3返回404时触发,根据请求路径自动重定向到对应目录的index.html;资源存在则直接返回原响应。
创建Node.js函数,代码如下:
'use strict'; exports.handler = async (event) => { const response = event.Records[0].cf.response; const request = event.Records[0].cf.request; const statusCode = response.status; // 仅处理S3返回的404情况 if (statusCode === '404') { const uri = request.uri; // 判断请求路径所属的应用目录 if (uri.startsWith('/subdirectory/')) { return { status: '200', statusDescription: 'OK', headers: { 'location': [{ key: 'Location', value: '/subdirectory/index.html' }] } }; } else { return { status: '200', statusDescription: 'OK', headers: { 'location': [{ key: 'Location', value: '/index.html' }] } }; } } // 资源存在时直接返回原响应 return response; };
创建完成后,发布函数的新版本(Lambda@Edge需要关联已发布的版本)。
2. 关联Lambda@Edge到CloudFront行为
- 打开CloudFront控制台,找到目标分发,切换到「行为」标签页
- 创建两个行为规则:
- 规则1:路径模式设为
/subdirectory/*,在「Lambda函数关联」区域,选择触发事件为「Origin Response」,关联刚才创建的Lambda@Edge函数版本 - 规则2:路径模式设为
/*,同样选择触发事件「Origin Response」,关联同一Lambda@Edge函数版本
- 规则1:路径模式设为
- 保存并等待CloudFront分发部署完成(通常需要10-15分钟)
测试验证
- 访问存在的资源(如
https://example.com/subdirectory/style/main.css):CloudFront直接返回S3中对应的文件 - 访问不存在的子目录路径(如
https://example.com/subdirectory/page1):自动返回subdirectory/index.html - 访问不存在的根路径(如
https://example.com/page2):自动返回根目录的index.html
内容的提问来源于stack exchange,提问作者Tom Baner
相关产品推荐
相关产品推荐

