Reputation: 257
I have a CloudFront function set up to set cache-control headers per status code. For status code 200 I want to use the custom response header cache-control set on my CloudFront distribution of max-age=604800, s-maxage=2592000. And for the other response codes I want the CloudFront function to set the cache-control as you can see in the following code. Every response is coming back with the cache-control of max-age=604800, s-maxage=2592000. How can I make it so the responses come back with the cache-control set by my CF function?
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;
}
I referenced this AWS article as a starting point https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/example-function-add-cache-control-header.html
I am using the JS Runtime 1.0
I have inspected my CloudFront distributions behaviors and can't place where I am going wrong.
I have the CF distribution referencing a response headers policy with a custom header with cache-control max-age=604800, s-maxage=2592000 and origin override enabled.
Does the response headers policy with a custom header take precedence over a CF function setting this header value?
Upvotes: 0
Views: 182
Reputation: 257
It turns out that this is not possible. Per https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-status-codes
"CloudFront does not invoke edge functions for viewer response events when the origin returns HTTP status code 400 or higher."
So I am going to set a shorter cache control in the custom response header and then set a longer one for 200 in the CloudFront function.
Upvotes: 0