gzip support for Amazon Web Services CloudFront

by Stephen Haynes on November 10, 2010

A common best practice when building high performance web sites is to serve gzip compressed versions of content such as JavaScript or CSS. Combining gzip compression with a content delivery network (CDN) can dramatically increase the performance of your web site by serving smaller files to users from a location that is closer to them, thus reducing response time and making your sites load faster.

Until now you have been able to support the CDN part of this best practice by using Amazon Web Services CloudFront. However, unlike some other CDNs CloudFront did not support serving gzipped content in a standard manner by using the HTTP Accept-Encoding header that is sent by browsers to indicate their support for gzip compression. There were some workarounds for this issue but they were far from optimal.

With the recent announcement of Custom Origin support in CloudFront it is now possible to use the standard HTTP Accept-Encoding method for serving gzipped content if you are using a Custom Origin. Although not specifically mentioned in the release announcement you can verify this in the Custom Origins Best Practices section of the CloudFront Developer Guide. CloudFront will now forward the Accept-Encoding HTTP header to your origin server where you can ensure the appropriate content is served based on the supported encodings. CloudFront will then cache multiple versions of this content, the uncompressed version and the gzipped version and serve these to clients depending on the value of their Accept-Encoding header for all future requests.

To support this feature on your origin server it should be configured to compress content of the appropriate type when the Accept-Encoding header is present.

For Apache 2.x this means ensuring mod_deflate is loaded and the appropriate content types are sent to the DEFLATE filter with the AddOutputFilterByType directive.

For nginx you need a configuration similar to the following:

gzip on;
gzip_http_version 1.0;
gzip_proxied any;
gzip_types text/css application/x-javascript;
gzip_vary on;

It’s important to note that CloudFront will only make HTTP/1.0 requests to an origin server, thus the requirement for gzip_http_version 1.0 in the nginx configuration. This is also noted in the Custom Origins Best Practices.