我有存储在 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-cache 的值:第一次加载时出现“来自云端的错误”(状态 200 并且图像加载正常)