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

为CloudFront上不同S3源配置差异化错误处理行为

解决方案:通过Lambda@Edge为CloudFront不同路径定制404错误处理

核心实现逻辑

利用Lambda@Edge的Origin Response触发阶段,在S3源返回404状态码时,根据请求路径区分多页站和SPA场景:

  • 对于/app*路径的404请求,重写响应为返回SPA的index.html,让前端路由接管处理
  • 非SPA路径的404请求,保持CloudFront原有配置的404.html响应

Lambda@Edge函数代码(Node.js)

exports.handler = async (event) => {
    const { response, request } = event.Records[0].cf;
    const { status } = response;

    // 仅处理404错误场景
    if (status !== '404') {
        return response;
    }

    // 判断请求是否属于SPA路径前缀
    const isSpaPath = request.uri.startsWith('/app/') || request.uri === '/app';
    if (!isSpaPath) {
        return response;
    }

    // 构造请求获取SPA的index.html内容
    const fetch = require('node-fetch');
    try {
        const indexRes = await fetch(`https://${request.headers.host}/app/index.html`);
        const indexContent = await indexRes.text();

        // 返回修改后的200响应
        return {
            status: '200',
            statusDescription: 'OK',
            headers: {
                'content-type': [{ key: 'Content-Type', value: 'text/html;charset=UTF-8' }],
                'cache-control': [{ key: 'Cache-Control', value: 'no-cache, no-store, must-revalidate' }],
                'content-length': [{ key: 'Content-Length', value: Buffer.byteLength(indexContent, 'utf8').toString() }]
            },
            body: indexContent,
            bodyEncoding: 'text'
        };
    } catch (err) {
        // 兜底:如果获取index.html失败,返回原始404或自定义错误
        console.error('Failed to fetch SPA index.html:', err);
        return response;
    }
};

配置步骤

  1. 创建Lambda函数:必须在us-east-1区域创建Node.js 18.x及以上版本的函数,粘贴上述代码并发布一个版本(不能使用$LATEST版本关联CloudFront)。
  2. 配置权限:确保Lambda执行角色的信任策略包含edgelambda.amazonaws.com,并且CloudFront有权限调用该Lambda函数(可通过Lambda控制台的"添加触发器"自动配置权限)。
  3. 关联到CloudFront:
    • 打开目标CloudFront分发的行为设置,找到/app*的附加行为。
    • 在Lambda Function Associations部分,选择Origin Response触发类型,关联已发布的Lambda函数版本。
  4. 验证:
    • 访问example.com/app/non-existent-page,应返回SPA的index.html(状态码200)
    • 访问example.com/non-existent-page,应返回多页站的404.html(状态码404)

关键注意事项

  • 性能优化:如果频繁触发该函数,建议将SPA的index.html缓存到CloudFront,减少内部请求的延迟;或者修改函数直接从S3桶读取index.html(需给Lambda角色添加S3读权限)。
  • 缓存策略:SPA的index.html通常不适合长期缓存,所以设置no-cache类的缓存头,确保用户能获取最新版本。
  • 错误兜底:函数中添加了异常捕获,避免因获取index.html失败导致5xx错误影响用户体验。

内容的提问来源于stack exchange,提问作者colioli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:50:25