CloudFront关联S3源时VIEWER_RESPONSE函数未触发问题求助
问题:仅针对CloudFront后S3源的404请求返回index.html
我的应用部署在CloudFront之后,多数路径由外部API提供支持,所有UI资源存储在S3中。需求是仅针对S3源的所有404请求返回index.html文件。
此前配置了全局errorResponse,将所有404请求响应为index.html,虽满足了S3的需求,但也导致API的404请求被替换为200状态并返回index.html内容,不符合预期。
为此我做了以下配置调整:
1. 编写CloudFront Function代码
function handler(event) { if (event.response.statusCode === 404) { event.response.statusCode = 501; event.response.statusDescription = 'Not Implemented'; } return event.response; }
2. 通过CDK将函数关联到S3源的默认行为
defaultBehavior: { origin: new S3Origin(Bucket.fromBucketName(this, 'UIResourcesBucket', props.uiResourcesBucketName)), compress: true, viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS, allowedMethods: AllowedMethods.ALLOW_GET_HEAD, cachePolicy: CachePolicy.CACHING_OPTIMIZED, originRequestPolicy: OriginRequestPolicy.CORS_S3_ORIGIN, responseHeadersPolicy: uiResponseHeadersPolicy, functionAssociations: [ { function: new Function(this, 'UIResources404Function', { code: FunctionCode.fromFile({ filePath: 'resources/cloudfront_function_redirect_404.js' }), }), eventType: FunctionEventType.VIEWER_RESPONSE, }, ], },
3. 更新全局errorResponse配置
改为针对501状态进行处理(API不会返回501):
errorResponses: [ { httpStatus: 501, ttl: Duration.seconds(30), responseHttpStatus: 200, responsePagePath: '/index.html', } ],
当前遇到的问题
所有配置已成功部署,非默认行为的API请求现在可正确返回404,但针对默认行为(S3源)的请求,当S3中无对应对象时仍返回404错误:
<Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>aadsiaodhai</Key> <RequestId>removed</RequestId> <HostId>removed</HostId> </Error>
测试请求未被CloudFront缓存(响应头显示x-cache: Error from cloudfront),我已对/*执行缓存失效操作。通过AWS控制台测试该CloudFront Function时,输入404状态可正确输出501,且函数已部署至Live状态,但监控面板显示该函数从未被调用。
疑问
使用S3源时CloudFront Functions有何限制?或有其他方法可实现仅S3源404返回index.html的需求?
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

