AWS ELB 重写路径并更改其间的路径

Wil*_*lie 5 amazon-web-services amazon-elb

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

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

当请求进入时:

example.org/api/foo/*

我需要将其重定向到:

example.org/api/v1/foo/*

请求的其余部分需要保持不变。问题是路径的原始值不能改变。原因的一种方法是将所有可能的路径添加为规则。但是在扩展api时会非常不舒服。

Tie*_*men 15

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

一些选项:

1)在ALB和您的应用程序之间实现一个Web服务器,例如nginx,它可以实现重写规则

Route53 -> CloudFront -> Lambda -> ALB2) 基于路径的重写可以通过使用, 而不是直接使用 来实现Route53 -> ALB,如此处所示


Yuc*_*uci 5

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

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

以下是此博客中的Lambda@Edge函数重写 URL 的示例Node.js

'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);

};
Run Code Online (Sandbox Code Playgroud)

顺便说一句,由于 AWS 边缘站点和 AWS 优化的专用网络路径等,在 ALB 之前或一般情况下使用 CloudFront 通常是有利的。ELB

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

因此,值得考虑使用Lambda@EdgeURL 重写,并带来CloudFront.