重定向到另一个域名,同时保留路径,使用AWS Lambda。

huangapple go评论57阅读模式
英文:

redirecting to another domain with AWS lambda whilst keeping the path

问题

https://aws.amazon.com/blogs/compute/redirection-in-a-serverless-api-with-aws-lambda-and-amazon-api-gateway/ 介绍了如何使用AWS Lambda进行HTTP 301/302重定向,但似乎没有讨论如何在保留路径的情况下执行重定向。

以下是他们提供的代码:

// 返回 302 或 301
var err = new Error("HandlerDemo.ResponseFound Redirection: Resource found elsewhere");
err.name = "http://a-different-uri";
context.done(err, {});

与其将请求从 http://oldwebsite.com/aaa 重定向到 http://newwebsite.com/,我想将它们重定向到 http://newwebsite.com/aaa

有关如何实现这一点的想法吗?

英文:

https://aws.amazon.com/blogs/compute/redirection-in-a-serverless-api-with-aws-lambda-and-amazon-api-gateway/ talks about how to do HTTP 301/302 redirects with AWS Lambda but it doesn't seem to discuss how to do the redirect whilst preserving the path.

Here's the code that they provide:

// Returns 302 or 301
var err = new Error("HandlerDemo.ResponseFound Redirection: Resource found elsewhere");
err.name = "http://a-different-uri";
context.done(err, {});

Instead of directing requests from http://oldwebsite.com/aaa to http://newwebsite.com/ I'd like to direct them to http://newwebsite.com/aaa.

Any ideas as to how I might do that?

答案1

得分: 1

我在快速测试中进行了黑客攻击,重新使用了文章中的方法:

  • 一个REST API,
  • 一个返回错误的Lambda,
  • 一个将错误转换为HTTP重定向的集成。

请求的路径位于event.path属性中,因此示例仅需要进行轻微更新:

exports.handler = async (event, context) => {
    const path = event?.path;
    var err = new Error('CustomError');
    err.name = 'http://newwebsite.com' + path;
    throw err;
};

另外需要注意的是,对于系统性重定向,HTTP API 可能更合适。在这种情况下,路径通过另一个属性(即event.rawPath)传入,Lambda 的结果将更像是一个HTTP响应。

英文:

I hacked a quick test, reusing the approach in the article:

  • a REST API,
  • a Lambda returning an error,
  • an integration transforming the error into an HTTP redirect.

The requested path comes in the event.path attribute, so the example requires only minor updates:

exports.handler = async (event, context) => {
    const path = event?.path;
    var err = new Error('CustomError');
    err.name = 'http://newwebsite.com' + path;
    throw err;
};

A a side note, an HTTP API is probably a better fit for a systematic redirect.
In this case the path is coming through another attribute (ie. event.rawPath) and the Lambda result will look more like an HTTP response.

huangapple
  • 本文由 发表于 2023年7月14日 02:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定