Set content expires and cache-control metadata for AWS S3 objects with Ruby

You can set the HTTP Expires and Cache-control headers for S3 bucket objects with the Ruby SDK for AWS. This will help site performance by enabling browsers to cache content which is not updated frequently such as stylesheets, javascript files and images.

This assumes you already have the AWS Ruby SDK installed.

require 'rubygems'
require 'aws-sdk'

s3 = AWS::S3.new(
  :access_key_id => 'your_access_key',
  :secret_access_key => 'your_secret_access_key')

bucket = s3.buckets['bucket_name']

one_year_in_seconds = 365 * 24 * 60 * 60
one_year_from_now = Time.now + one_year_in_seconds

# for a new object / to update an existing object
o = bucket.objects['object']
o.write(:file => 'path_to_file', 
    :cache_control => "max-age=#{one_year_in_seconds}", 
    :expires => one_year_from_now.httpdate)

# to update an existing object
o.copy_to(o.key, 
    :cache_control => "max-age=#{one_year_in_seconds}", 
    :expires => one_year_from_now.httpdate)

Note, writing this metadata via .write requires you to write the object data as well. You can set either, both or neither of the fields as appropriate. If you don’t provide the metadata fields when updating the object via .write, they will be removed from the item on S3.

An alternative for updating an object is to copy the object to itself using the .copy_to method. When copying an object, existing values for these fields are preserved rather than removed if not updated.

Tags: