【问题标题】:How to configure CloudFront 403 redirection when hosting multiple Single Page Apps in one CloudFront Distribution and one S3 bucket origin在一个 CloudFront 分配和一个 S3 存储桶源中托管多个单页应用程序时如何配置 CloudFront 403 重定向
【发布时间】:2020-10-12 16:24:31
【问题描述】:

我的目标是为我们在 Git 中拥有的每个分支托管一个网站版本。我有以下设置,似乎大部分都按预期工作:

  1. 每个构建都有一个目录的 S3 存储桶
  2. 一个 GitHub Actions 作业,用于在文件更改时构建应用程序,并将代码部署到 S3 存储桶中的相应目录
  3. 用于位于 S3 存储桶顶部的网站的 CloudFront 分配。它使用通配符证书和 Lambda@Edge 查看器请求函数将请求的子域转换为 URI 路径 (https://branch.dev.company.com/ -> dev.company.com/branch/index.html)。我需要这样做,因为开发人员已经使用绝对 URI 在内部编写了带有重定向的应用程序。

通常对于单页应用程序,我会将自定义 403 响应设置为直接指向 /index.html 由于我在不同的地方有多个 index.html 页面,我不知道如何将其指向适当的索引。 html。感觉我需要一个选项来重定向到 %SITE_URL%/index.html

【问题讨论】:

    标签: amazon-s3 single-page-application amazon-cloudfront


    【解决方案1】:

    这是你的幸运日!

    https://github.com/marksteele/edge-rewrite

    该项目旨在提供一种利用 Lambda@Edge 运行 URI/URL 重写功能的机制。 如果您在 CloudFront 后面部署您的网站,您现在可以在 CDN 边缘重写 URL,并避免在后端服务器上浪费 CPU 周期。

    规则格式类似于mod_rewrite使用的格式。

    <REGEX> <OPTIONAL REPLACEMENT> [<FLAGS>]
    

    规则的第一部分是正则表达式,后跟可选的新路径或 URL 和可选标志。

    在您的情况下,您想要 URL 重写:
    https://branch.dev.company.com/

    进入这个新网址:
    https://dev.company.com/branch/index.html

    现在是最困难的部分,RegEx!幸运的是,Edge-Rewrite 的规则格式类似于 mod_rewrite 使用的格式,我能够找到这个mod-rewrite subdomain to path in primary domain

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} ^sub\.company\.com$ [NC]
    RewriteRule ^ http://company.com/sub%{REQUEST_URI} [R=301,L,NE]
    

    以上内容应该有助于制作类似于示例所示的内容:

    ^/oldpath/(\\d*)/(.*)$ /newpath/$2/$1 [L]
    

    另外,一种更快、更容易、更易读和可维护的方法是自己编写重定向。我根据这篇优秀的文章为你定制了这段代码:https://faragta.com/aws-cloudfront/rewrite-url.html:

      'use strict';
        exports.handler = (event, context, callback) => {
            
            // Get request from CloudFront event  
            var request = event.Records[0].cf.request;
        
            // Extract the URI from the request
            var requestUrl = request.uri;
        
            // Rewrite the Subdomain to a Route to redirect to a different Branch
            var n = requestUrl.indexOf(".");  
            const protocolLen = 7;   //"https://"
            var branch = requestUrl.substring(protocolLen + 1, n - 1);  
            redirectUrl = requestUrl.substring(0, protocolLen) + requestUrl.substring(protocolLen + branch.length + 1) + branch + "/index.html";  
    
            // Replace the received URI with the URI that includes the index page
            request.uri = redirectUrl;
            
            // Return to CloudFront
            return callback(null, request);
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-23
      • 2021-10-07
      • 1970-01-01
      • 2020-04-24
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      相关资源
      最近更新 更多