You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:23:31