我们将创建一个 CloudFront Function,将特定路径的请求redirect到另一个路径:
/catalog/spices/ -> https://aws.amazon.com/
前往CloudFront ,并在左侧导航栏中选择 Functions。点击"Create function"开始操作:

设置函数的名称、描述(可选)和运行时:
test-redirectcloudfront-js-2.0 运行时点击 Create Function 按钮:

函数创建完成后,我们需要编写代码, 以下是我们 CloudFront Function 的代码要求:
/catalog/spices/https://aws.amazon.comheaders 的 location 中可以根据上面的这些描述给AI IDE来写
如果想自己编写其他函数,请查看文档 ,其中包含示例代码。
可直接使用以下代码:
function handler(event) {
var request = event.request;
var uri = request.uri;
// Check if the request URI matches the path to redirect
if (uri === "/catalog/spices/") {
// Construct the new URL to redirect to
var newUrl = "https://aws.amazon.com/";
// Create the redirect response
var response = {
statusCode: 302, // HTTP 302 Redirect
statusDescription: "Found",
headers: {
location: { value: newUrl }
}
};
// Return the redirect response
return response;
}
// If the request doesn't match, return the original request
return request;
}
点击保存:

点击右侧的test
对于 Event type,将其设置为 viewer request,因为这是我们希望触发重定向的阶段
接下来为 HTTP method 选择 GET
将 URL path 设置为 /catalog/spices/,以满足函数中重定向的条件
点击 Test function。

测试应显示以下内容:
