AWS ELB 重写路径并改变两者之间的路径

AWS ELB rewrite path and alter the path in between

我在 Amazon Webservices(特别是应用程序负载均衡器)上使用 ELB(弹性负载均衡器)。

问题: 我想创建一个规则来重写路径,但需要在路径中插入一个字符串。

当请求进入时:

example.org/api/foo/*

我需要将它重定向到:

example.org/api/v1/foo/*

请求的其余部分需要保持不变。 问题是路径的原始值无法更改。原因的一种方式是作为规则添加每条可能的路径。但是在展开api的时候会很不舒服

正如您已经发现的,ELB 不支持重写。

部分选项:

1) 实施网络服务器,例如ALB和你的应用之间的nginx,可以实现重写规则

2) 基于路径的重写可以通过使用 Route53 -> CloudFront -> Lambda -> ALB 而不是直接 Route53 -> ALB 来实现,如 here.

所示

目前一个不错的选择是利用Lambda@Edge实现URL重写。

Lambda@Edge 是 Amazon CloudFront 的一项功能,可让您 运行 在全球范围内更贴近用户的代码。 Lambda@Edge 函数在请求发送到负载均衡器之前被触发。

这里是 URL 由 Node.js 中的 Lambda@Edge 函数从 this blog

重写的示例
'use strict';
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;

    // 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(/\/$/, '\/index.html');
    
    // Log the URI as received by CloudFront and the new URI to be used to fetch from origin
    console.log("Old URI: " + olduri);
    console.log("New URI: " + newuri);
    
    // Replace the received URI with the URI that includes the index page
    request.uri = newuri;
    
    // Return to CloudFront
    return callback(null, request);

};

顺便说一下,总的来说,it is normally advantageous to have CloudFront in front of an ALBELB,这要归功于 AWS 边缘位置和 AWS 优化的私有网络路径等

对于某些用例,前面带有 CloudFront 的另一个好处是静态内容(例如 HTML、JavaScript、CSS 和图像文件等)和动态 API 可以共享相同的域和 SSL 证书,通过在 CloudFront 分发中配置多个来源和多个行为,请参阅 了解详细信息。

因此值得考虑使用 Lambda@Edge 进行 URL 重写,以及 CloudFront 带来的附加好处。