具有多个基于路径的单页应用程序的 S3/Cloudfront 客户端路由

Nic*_*ley 5 amazon-s3 amazon-web-services amazon-cloudfront single-page-application react-router

我有以下情况:

  • 具有多个基于路径的应用程序的 S3 存储桶,按版本号分组。简化示例:
/v1.0.0
  index.html
  main.js
/v1.1.0
  index.html
  main.js
Run Code Online (Sandbox Code Playgroud)
  • 每个应用程序都是一个 (React) SPA,并且需要客户端路由(通过 React 路由器)

我正在将 S3 与 Cloudfront 结合使用,并且一切正常,但客户端路由已损坏。这就是说我能够访问每个应用程序的根目录,即。https://<app>.cloudfront.net/<version>,但无法到达任何客户端路由。

我知道可以将错误文档设置为重定向到index.html,但我相信此解决方案仅在每个存储桶都有一个时才有效index.html(即,我无法为每个基于路由的路径设置错误文档)。

解决这个问题的最佳方法是什么?

use*_*287 6

通过 Cloudfront 处理 SPA 的一种简单方法是使用 Lambda@Edge - Origin 请求(或Cloudfront 函数)。目标是更改 Origin URI。

我经常在 SPA 中使用的简单 js 代码(对于 v1.0.0 web 应用程序):

exports.handler = async (event) => {
   const request = event.Records[0].cf.request;
   const hasType = request.uri.split(/\#|\?/)[0].split('.').length >= 2;
   if (hasType) return request; // simply forward to the S3 object as it is an asset
   request.uri = '/v1.0.0/index.html'; // handle all react routes
   return request;
};
Run Code Online (Sandbox Code Playgroud)

我检查 URL 中是否有扩展名(.png、.js、.css、...)。如果它是资产,我只需转发到 S3 对象,否则我发送 index.html。
在这种情况下,index.html 将发送到路径 /v1.0.0/my-react-router。

更新
对于动态处理,您可以这样做(为了这个想法):
request.uri = '/' + request.uri.split('/')[1] + '/index.html';

或者更好的是,使用正则表达式来解析request.uri以提取版本、资产的扩展名或 spa 路由。