这是你的幸运日!
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);
};