Amazon S3, CSS, Gzip and Safari

25 Sep
2009

We use a Amazon S3 a lot. It’s a great service that can get expensive if you have a lot of traffic, or a lot of bandwidth.

With this in mind (and also trying to keep page weight down on what is fast becoming a bloaty homepage), I set about trying to serve the CSS files GZIPped.

With our normal server, we would have probably used PHP to do this using the ob_gzhandler (great tutorial on how to do this at addedBytes). But, of course, this is Amazon S3 – we can’t get PHP to gzip files up on the fly.

Undeterred, I got a copy of S3 Hub and gzipped my CSS files (to GZIP your CSS files, open Terminal and type gzip /path/to/your/css/files/style.css)

Then, open up S3 Hub, connect to your bucket and upload the files; set permissions if you need; then right click a GZIPped CSS file and choose ‘Header’. Make sure that you have Content-Encoding set to ‘gzip’ and Content-Type set to ‘text/css’.  Hit Save.

Now, you’re going to have to rename your files.

Chances are that your files are named myStyle.css.gz or just myStyle.gz. For Safari to interpret your CSS file correctly, it needs to be called myStyle.gz.css – it has to end in .css. Without this, Safari will treat it as a gzip file.

Once you’ve done that, you’re almost there.

Stick this above your meta –

1
if(isset($_SERVER['HTTP_ACCEPT_ENCODING'])){ define('GZ',strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false ? 'gz.' : '');} else { define('GZ','') ; }

And then this next to all your css links

1
<link rel="stylesheet" type="text/css" href="<?=PATH_TO_YOUR_AMAZON_S3_BUCKET?>css/myStyle.<?=GZ?>css" />

So, on browsers that can accept gzip files they will get

1
<link rel="stylesheet" type="text/css" href="https://s3.amazonaws.com/twitter_production/a/1253830975/stylesheets/twitter-https.gz.css" />

rather than

1
<link rel="stylesheet" type="text/css" href="https://s3.amazonaws.com/twitter_production/a/1253830975/stylesheets/twitter-https.css" />

Twitter don’t Gzip their CSS, by the way. If they did they would be saving 46,227 bytes per unique user. They use long expiry dates instead. But there’s no reason you can’t do this, too.

Go into S3 Hub again and choose header again. This time choose ‘Expires (Far Future)’. Job done.

You do need to remember that if you change the file, you will have to upload a new version (2 new versions – 1 gzipped and one normal) and rename it, so that those users who have visited and have your CSS file cached will be able to see the changes you have made.

So, we are saving lots of bandwidth from a few lines of code, and I would thoroughly recommend it to anyone. The only thing that took a fair bit of time was working out why it wasn’t working in Safari, but once I had that sorted, it was plain sailing.

(this post previously appeared on bring back tables)

Comment Form

top