且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在同一URL下在S3 + Cloudfront上托管多个SPA Web应用程序

更新时间:2021-12-07 06:24:29

研究了此问题之后,我能够使用lambda @ edge(

After researching this issue, I was able to resolve it using lambda@edge (https://aws.amazon.com/lambda/edge/)

通过部署简单的javascript函数将特定路径路由到所需的s3存储桶,我们可以实现类似nginx的路由设置. 该函数位于我们的Cloudfront CDN上的lambda @ edge上,这意味着您可以指定何时被触发.对我们来说,它是在原产地请求"上

By deploying a simple javascript function to route specific paths to the desired s3 bucket, we are able to achieve an nginx-like routing setup. The function sits on lambda@edge on our Cloudfront CDN, meaning you can specify when it is triggered. For us, it's on "Origin Request"

我的设置如下:

  • 我使用了一个s3存储桶,并将第二个应用程序部署在子文件夹"second-app"中
  • 我创建了一个新的Lambda函数,该函数托管在美国东弗吉尼亚北部"上.该区域在这里很重要,因为您只能在该区域中托管lambda函数@edge.
  • 有关实际的Lambda函数,请参见下文
  • 创建后,转到您的CloudFront配置并转到行为>选择默认(*)路径模式,然后单击编辑"
  • 滚动到有"Lambda函数关联"的底部
  • 从下拉列表中选择来源请求"
  • 输入您的lambda函数(arn:aws:lambda:us-east-1:12345667890:function:my-function-name)的地址
  • I used a single s3 bucket, and deployed my second-app in a subfolder "second-app"
  • I created a new Lambda function, hosted on "U.S. East N Virginia". The region is important here, as you can only host lambda function an @edge in this region.
  • See below for the actual Lambda function
  • Once created, go to your CloudFront configuration and go to "Behaviors > Select the Default (*) path pattern and hit Edit"
  • Scroll to the bottom where there is "Lambda Function Associations"
  • Select "Origin Request" form the drop down
  • Enter the address for your lambda function (arn:aws:lambda:us-east-1:12345667890:function:my-function-name)

这是我使用的lambda函数的示例.

Here is an example of the lambda function I used.


var path = require('path');

exports.handler = (event, context, callback) => {
  // Extract the request from the CloudFront event that is sent to Lambda@Edge
  var request = event.Records[0].cf.request;

  const parsedPath = path.parse(request.uri);

  // If there is no extension present, attempt to rewrite url
  if (parsedPath.ext === '') {
    // Extract the URI from the request
    var olduri = request.uri;

    // Match any '/' that occurs at the end of a URI. Replace it with a default index
    var newuri = olduri.replace(/second-app.*/, 'second-app/index.html');

    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;
  }
  // If an extension was not present, we are trying to load static access, so allow the request to proceed
  // Return to CloudFront
  return callback(null, request);
};

这些是我用于此解决方案的资源:

These are the resources I used for this solution:

  • https://aws.amazon.com/blogs/compute/implementing-default-directory-indexes-in-amazon-s3-backed-amazon-cloudfront-origins-using-lambdaedge/
  • https://github.com/riboseinc/terraform-aws-s3-cloudfront-website/issues/1
  • How do you set a default root object for subdirectories for a statically hosted website on Cloudfront?