使用 CloudFront 的 Gzip 压缩不起作用

Gzip compression with CloudFront doesn't work

我有一个 angular 应用程序,即使使用产品模式构建,它也有多个大文件(超过 1MB)。

我想使用 CloudFront 上的 gzip 压缩功能来压缩它们。

我在 CloudFront 控制台中激活了 "Compress Objects Automatically" 选项。我的分发源是一个 s3 存储桶。

但是当我通过我的浏览器加载页面时下载的包没有用 gzip 压缩

这里有一个 request/response

的例子

请求header:

:authority:dev.test.com
:method:GET
:path:/vendor.cc93ad5b987bea0611e1.bundle.js
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
cache-control:no-cache
pragma:no-cache
referer:https://dev.test.com/console/projects
user-agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36

回应header

accept-ranges:bytes
age:17979
content-length:5233622
content-type:text/javascript
date:Tue, 07 Nov 2017 08:42:08 GMT
etag:"6dfe6e16901c5ee5c387407203829bec"
last-modified:Thu, 26 Oct 2017 09:57:15 GMT
server:AmazonS3
status:200
via:1.1 9b307acf1eed524f97301fa1d3a44753.cloudfront.net (CloudFront)
x-amz-cf-id:9RpiXSuSGszUaX7hBA4ZaEO949g76UDoCaxzwFtiWo7C-wla-PyBsA==
x-cache:Hit from cloudfront

根据 AWS 文档,一切正常:

你知道为什么 cloudfront 不压缩我的文件吗?

动态 GZip 压缩由 CloudFront 尽最大努力处理。基于边缘位置的容量和可用性。

要获得可预测的压缩,您需要在上传到 S3 之前对它们进行 gzip。

这个响应是几个小时前缓存的。

age:17979

CloudFront 不会返回并 gzip 已缓存的内容。

CloudFront compresses files in each edge location when it gets the files from your origin. When you configure CloudFront to compress your content, it doesn't compress files that are already in edge locations. In addition, when a file expires in an edge location and CloudFront forwards another request for the file to your origin, CloudFront doesn't compress the file if your origin returns an HTTP status code 304, which means that the edge location already has the latest version of the file. If you want CloudFront to compress the files that are already in edge locations, you'll need to invalidate those files.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html

执行缓存失效,等待其完成,然后重试。

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html