Lambda @ Edge缓存控制标头不存在Cloudfront

时间:2019-05-09 21:24:52

标签: amazon-s3 header amazon-cloudfront cache-control aws-lambda-edge

我将图像存储在S3上,并使用lambda函数即时调整它们的大小。在执行此操作时,我将CacheControl: 'max-age=31536000'添加到调整大小的图像中,还添加了一个Cache-Control标头:

.then(buffer => {
  // save the resized object to S3 bucket with appropriate object key.
  S3.putObject({
    Body: buffer,
    Bucket: BUCKET,
    ContentType: 'image/jpg',
    CacheControl: 'max-age=31536000',
    Key: `uploads/${key}`,
  })

  // generate a binary response with resized image
  response.status = 200
  response.body = buffer.toString('base64')
  response.bodyEncoding = 'base64'
  response.headers['content-type'] = [{ key: 'Content-Type', value: 'image/jpg' }]
  response.headers['cache-control'] = [{ key: 'Cache-Control', value: 'public, max-age=31536000' }]
  callback(null, response)
})

如果缩略图已经生成,我就这样做:

if (!response.headers['cache-control']) {
  response.headers['cache-control'] = [{ key: 'Cache-Control', value: 'public, max-age=31536000' }]
}
callback(null, response)

在Cloudfront发行版中,我具有以下设置:

  • 基于所选请求标头的缓存:无
  • 对象缓存:使用原始缓存头

lambda可以正常工作,但是当我查看devtools时,Chrome似乎从不缓存图像。这是我得到的信息:

General
  Request URL: https://aws.mydomain.com/478/dd123cd5-1636-47d0-b756-e6c6e9cb28c0/normal/pic.jpg
  Request Method: GET
  Status Code: 200 
  Remote Address: 52.84.31.149:443
  Referrer Policy: no-referrer-when-downgrade
  age: 382

Response Headers
  content-length: 49192
  content-type: image/jpg
  date: Thu, 09 May 2019 20:41:42 GMT
  server: AmazonS3
  status: 200
  via: 1.1 261e801dca9c54ff576f39f96d80ede5.cloudfront.net (CloudFront)
  x-amz-cf-id: ZlheiBoNDuYDeuvZo0jBP6Zjpge5AonPGlCo_N2pHhHdGwV7DorKtA==
  x-amz-id-2: xkDxIB0qDJt5KMeHINq7/gaRII6EDBOsL3SlMuhMwJ84M/lak9E/tcRChv7vvYurD+2hYOT8kSI=
  x-amz-request-id: CAD9AE1E905BB13A
  x-cache: Hit from cloudfront

Request Headers
  :authority: aws.mydomain.com
  :method: GET
  :path: /478/dd123cd5-1636-47d0-b756-e6c6e9cb28c0/normal/pic.jpg
  :scheme: https
  accept: */*
  accept-encoding: gzip, deflate, br
  accept-language: en-US,en;q=0.9
  user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36

不存在Control-Cache,我无法弄清楚...

当我使发行版中的所有图像失效时,唯一的变化是x缓存的值:第一次加载时出现“ Cloudfront错误”(状态200,图像加载正常)

1 个答案:

答案 0 :(得分:0)

好吧,因此显然不可能在原始响应lambda中添加缓存控制标头。您必须在查看者响应lambda中执行此操作。像这样:

exports.handler = (event, context, callback) => {
  const response = event.Records[0].cf.response;
  if (!response.headers['cache-control']) {
    response.headers['cache-control'] = [{
      key: 'Cache-Control',
      value: 'max-age=31536000'
    }];
  }
  callback(null, response);
};