CloudFront 功能缓存控制标头不会更改 CF 发行版中设置的自定义响应标头

问题描述 投票:0回答:1

我设置了一个 CloudFront 函数来根据状态代码设置缓存控制标头。对于状态代码 200,我想使用在我的 CloudFront 分配上设置的自定义响应标头缓存控制 max-age=604800、s-maxage=2592000。对于其他响应代码,我希望 CloudFront 函数设置缓存控制,如以下代码所示。每个响应都会返回 max-age=604800、s-maxage=2592000 的缓存控制。我怎样才能做到这一点,以便响应通过我的 CF 函数设置的缓存控制返回?

var DEBUG = true;

function logToConsole(message, force) {
    if (DEBUG || force !== undefined) console.log(message);
}

var cacheControlHeaders = {
    404: 'max-age=300',
    403: 'max-age=0',
    400: 'max-age=0',
    500: 'max-age=0',
    503: 'max-age=0',
    504: 'max-age=0'
};

function handler(event) {
    logToConsole(event);
    try {
        var statusCode = event.response.statusCode;
        logToConsole(statusCode);
        
        if (cacheControlHeaders.hasOwnProperty(statusCode)) {
            var cacheControlValue = cacheControlHeaders[statusCode];
            logToConsole(`Setting Cache-Control for ${statusCode} response`);
            event.response.headers['cache-control'] = { value: cacheControlValue };
        }
    } catch (error) {
        logToConsole(error, true);
    }

    return event.response;
}

我引用这篇 AWS 文章作为起点 https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/example-function-add-cache-control-header.html

我使用的是 JS Runtime 1.0

我已经检查了我的 CloudFront 发行版行为,但无法找出出错的地方。

我的 CF 发行版引用了带有自定义标头的响应标头策略,其中缓存控制 max-age=604800、s-maxage=2592000 并启用了原始覆盖。

具有自定义标头的响应标头策略是否优先于设置此标头值的 CF 函数?

amazon-cloudfront cloudfront-functions
1个回答
0
投票

事实证明这是不可能的。根据 https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-status-codes

“当源返回 HTTP 状态代码 400 或更高版本时,CloudFront 不会调用查看器响应事件的边缘函数。”

因此,我将在自定义响应标头中设置一个较短的缓存控制,然后在 CloudFront 函数中设置一个较长的缓存控制(200)。

© www.soinside.com 2019 - 2024. All rights reserved.