【问题标题】:Can Cloudfront + ELB change the query string of my request?Cloudfront + ELB 可以更改我的请求的查询字符串吗?
【发布时间】:2021-05-27 11:18:51
【问题描述】:

我们正在 AWS 上运行一个 React Web 应用程序。 Web 应用程序由 S3 存储桶托管,API 位于弹性 beanstalk 上。我们使用 Cloudfront 将其整合到单个域中。

到目前为止一切顺利。网站加载完毕,它可以与 API 对话。

问题是,所有到达我们的弹性 beanstalk 实例的 API 请求在查询字符串中仍然有 /api。这对我们的 API 来说很好,因为我们可以控制它,但是我们正在部署一个 tileserver-gl 的实例,它不允许我们配置要从其提供服务的根 url。

我似乎无法配置 Cloudfront 来修改查询字符串以删除第一部分。例如。这样mysite.com/api/v1/users 就会映射到fj935hf02.elasticbeanstalk.com/v1/users

其他人是如何绕过这个问题的?

【问题讨论】:

  • 你不能从源头做到这一点吗?
  • 你是什么意思?如果源请求除 /api 之外的任何内容,则该请求将不会到达 API 服务器。
  • 哦,我的错!!!!

标签: amazon-web-services amazon-cloudfront


【解决方案1】:

是的,CloudFront 可以通过Lamdba@edge 进行类似的修改。具体来说,您可以查看Origin request 函数,该函数可以修改传递给源的内容。

AWS 还提供了examples 的此类功能。 One 的示例展示了如何使用查询字符串。

'use strict';

const querystring = require('querystring');
exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    
    /* When a request contains a query string key-value pair but the origin server
     * expects the value in a header, you can use this Lambda function to
     * convert the key-value pair to a header. Here's what the function does:
     * 1. Parses the query string and gets the key-value pair.
     * 2. Adds a header to the request using the key-value pair that the function got in step 1.
     */

    /* Parse request querystring to get javascript object */
    const params = querystring.parse(request.querystring);

    /* Move auth param from querystring to headers */
    const headerName = 'Auth-Header';
    request.headers[headerName.toLowerCase()] = [{ key: headerName, value: params.auth }];
    delete params.auth;

    /* Update request querystring */
    request.querystring = querystring.stringify(params);

    callback(null, request);
};

【讨论】:

  • 谢谢!你有使用 Lamda@Edge 做这种事情的经验吗?你知道哪些陷阱?
  • @Hannesh Lambda@Edge 不是免费的,与常规 lambda 相比有很多限制。但是如果要修改标头或查询字符串,我不知道 CloudFront 有什么其他方式。
猜你喜欢
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2013-04-06
相关资源
最近更新 更多