Lambda仅读取S3中JSON重定向配置首个条目,其余失效问题求助
问题原因与修复方案
问题根源
你的Lambda函数逻辑存在错误:在遍历重定向条目时,第一次循环就会强制返回结果——如果第一个URL匹配,返回重定向响应;如果不匹配,直接返回原请求,导致后续的重定向条目完全没机会被检查,所以只有第一个条目生效。
修复后的代码
import boto3 import json s3 = boto3.resource('s3') base_url= "testsite_com" ###Cannot post any site address on stackoverflow def lambda_handler (event, context): request = event['Records'][0]['cf']['request'] print(event) content_object = s3.Object('cbtest.cb-infra.com', 'config/redirects.json') file_content = content_object.get()['Body'].read().decode('utf-8') json_content = json.loads(file_content) # 遍历所有重定向条目 for entry in json_content["redirects"]: old_url = entry["url"] redirect_uri = entry["redirect_url"] status_code = entry["statusCode"] new_url= base_url + redirect_uri print(f"Checking redirect rule: {old_url} -> {redirect_uri}") if request["uri"] == old_url : response = { 'status': status_code, 'statusDescription': 'Found' if status_code == 302 else 'Moved Permanently', 'headers': { 'location': [{ 'key': 'Location', 'value': new_url }] } } print(f"Redirecting: {request['uri']} -> {redirect_uri}") return response # 所有条目都不匹配时,返回原请求 print(f"No redirect rule matched for URI: {request['uri']}") return request
修改说明
- 移除了循环内部的
else分支,避免第一次不匹配就直接返回原请求 - 把返回原请求的逻辑移到循环结束之后,确保所有重定向条目都被检查
- 优化了
statusDescription,根据状态码返回对应的描述(302对应Found,301对应Moved Permanently),更符合HTTP规范 - 调整了打印日志,方便调试时查看规则检查情况
内容的提问来源于stack exchange,提问作者Rohan Hunnurkar
相关产品推荐
相关产品推荐

