使用Lambda@Edge配置CloudFront 301重定向时遇lambdaExecutionError
问题描述
我尝试使用Lambda@Edge在CloudFront上配置重定向,但持续收到模糊错误。以下是我的配置情况:
- 拥有一个带有“将HTTP重定向到HTTPS”行为的CloudFront分发;
- 在us-east-1区域创建了Lambda函数;
- 创建函数时选择了“Basic Lambda@Edge permissions (for CloudFront trigger)”权限模板;
- 我的Lambda函数代码如下;
- 在Lambda中测试代码时存在错误。
点击“Deploy to Lambda@Edge”时的操作:
- 选择我的CloudFront分发;
- 选择“Viewer request”作为CloudFront事件(不确定是否正确);
- 等待分发状态从“deploying”变为时间戳;
- 使用
/*路径使CloudFront缓存失效并等待完成; - 验证最新Lambda函数版本已关联到CloudFront分发的行为中。
使用curl访问URL时的现象:
- 收到503错误“lambdaExecutionError from cloudfront”;
- 查看最新Lambda函数版本的CloudWatch日志时显示“No data found”。
请问可能是什么原因导致该错误?
- 我的代码响应格式是否正确?
- “Viewer request”是否为正确的CloudFront事件?
export const handler = async (event, context) => { const { request, response } = event.Records[0].cf; var newLocation = ""; var statusCode = 301; var statusDescription = "Moved Permanently"; console.log(request); switch(request.uri) { case '/file1.pdf': newLocation = '/file2.pdf'; statusCode = 301; break; case '/file3.pdf': newLocation = '/file4.pdf'; statusCode = 301; break; } if (statusCode === 302) { statusDescription = "Found"; } if (newLocation !== "") { response.headers['location'] = [ { key: 'Location', value: newLocation, }, ]; return { status: statusCode, statusDescription: statusDescription, headers: response.headers, }; } else { return response; } };
问题解答
1. 代码响应格式问题
你的代码存在核心错误,直接导致了503错误:
- Viewer Request阶段无response对象:Viewer Request是在CloudFront转发请求到源站前触发的,此时
event.Records[0].cf结构里只有request,没有response。你直接解构response会触发未定义错误,这是Lambda执行失败的关键原因。 - 返回逻辑错误:Viewer Request事件中,无需重定向时应返回原始
request而非response;需要重定向时,要构造完整的响应对象,不能依赖不存在的response。
修正后的代码示例:
export const handler = async (event, context) => { const { request } = event.Records[0].cf; let newLocation = ""; let statusCode = 301; let statusDescription = "Moved Permanently"; switch(request.uri) { case '/file1.pdf': newLocation = '/file2.pdf'; break; case '/file3.pdf': newLocation = '/file4.pdf'; break; } if (statusCode === 302) { statusDescription = "Found"; } if (newLocation !== "") { return { status: statusCode, statusDescription: statusDescription, headers: { location: [{ key: 'Location', value: newLocation, }] } }; } else { // 无需重定向时返回原始请求 return request; } };
2. CloudFront事件类型选择
Viewer request是适合做URL重定向的正确事件类型。它在请求到达CloudFront后立即触发,能在缓存或转发到源站前完成重定向,避免不必要的源站请求和缓存污染。但要严格遵循该事件的规则:
- 只能返回
request对象或自定义响应对象 - 无法访问
response对象(仅Viewer Response、Origin Request/Response阶段才有)
额外排查要点
- Lambda本地测试:先在Lambda控制台选择CloudFront的Viewer Request模拟事件测试代码,确保能正常执行,避免因测试事件结构不匹配导致的错误。
- CloudWatch日志区域:Lambda@Edge的日志会生成在用户访问对应的边缘节点区域(而非us-east-1),切换到对应区域即可查看日志,解决“No data found”问题。
- 权限验证:确认Lambda执行角色信任关系包含
edgelambda.amazonaws.com,且具备logs:CreateLogGroup、logs:CreateLogStream、logs:PutLogEvents权限,确保日志能正常生成。
内容的提问来源于stack exchange,提问作者user366810
相关产品推荐
相关产品推荐

