Enable GZIP compression for Amazon S3 hosted website in CloudFront

By Robert Ellison. Updated on Sunday, August 11, 2024.

Enable GZIP compression for Amazon S3 hosted website in CloudFront

By default compression doesn't work in CloudFront for a website backed by an Amaxon S3 bucket.

The first step is pretty obvious - switch on compression in CloudFront:

Compress Objects Automatically option in Amazon CloudFront

To get to this setting open you distribution, go to the Behaviors tab and edit your behavior(s). Scroll down to the bottom and toggle Compress Objects Automatically to On. Save and drum your fingers while the distribution updates.

The less obvious piece is that CloudFront will only compress files between 1,000 and 10,000,000 bytes (as of writing this post) and it detects the filesize from the Content-Length header. What the documentation doesn't mention is that S3 does not send the Content-Length header by default and so no compression is applied.

Go to S3 and open the properties for your bucket (not for individual files). Expand Permissions and then click Edit CORS Configuration. You need to add Content-Length as an allowed header like this:

Add your comment...

Related Posts

(All Code Posts)

(Published to the Fediverse as: Enable GZIP compression for Amazon S3 hosted website in CloudFront #code #software #s3 #cloudfront #aws How to configure Amazon CloudFront to apply gzip compression for websites hosted using Amazon S3 (Simple Storage Service) )

Comments

Nowaker

The attached CORS configuration doesn't need to be added. It works just fine without it.

Here's a way to test compression from a Linux/OSX command line:

curl -sD - -o /dev/null -H 'Accept-Encoding: gzip' (URL)

Robert Ellison

Keith - I did not have to invalidate after making this change.

Keith

Do you have to invalidate the files in the CDN for the compression to take place? Or will it automatically do this one the "compress objects automatically" toggle is flipped to "Yes" ?

Robert Ellison

Hi atv, I'm not an expert on apache so you might need to look elsewhere for help. I assume that you mean apache as an origin server for CloudFront? It's the Content-Length header that is required for gzip compression. Allow origin is about cross origin requests and as far as I know has no implications for compression, I'm not sure why your file would be larger after changing this setting.

atv

Does this work for apache as well? I just added a allow-origin header in my httpd.conf for fixing CORS errors in chrome, but although gtmetrix shows 100/100, it seems to have increased the size of my webpage (but it's much faster).

So i'm unsure of what to do here.

josh

I appreciate this post

tj

you are my hero thanks, this fixed it

justin

Thanks a lot for this enlighting post.

It got it working for me.

Add Comment

All comments are moderated. Your email address is used to display a Gravatar and optionally for notification of new comments and to sign up for the newsletter.