How to add cache-control, expires headers to images (Content) served by S3

A few days back I made a blog post Save image as a progressive image using paperclip and imageMagick. Here is an another improvement in that list.

Adding cache control and expiry headers. Caching images improves the user experience and reduces S3 costs. It improves the user’s experience as web pages load quicker, images are already cached and it reduces S3 costs since you have fewer transfers.

From the previous blog post:

Before:

    has_attached_file :attachment, {
      :styles => {
        :medium => ["654x500>", :jpg],
        :thumb =>["200x200#", :jpg]
      }

After:

  has_attached_file :attachment, {
    :styles => {
      :medium => ["654x500>", :jpg],
      :thumb =>["200x200#", :jpg]
    },
    :convert_options => {
      :medium => "-quality 80 -interlace Plane",
      :thumb => "-quality 80 -interlace Plane"
      }
    }

Another improvement:

  has_attached_file :attachment, {
    :styles => {
      :medium => ["654x500>", :jpg],
      :thumb =>["200x200#", :jpg]
    },
    :convert_options => {
      :medium => "-quality 80 -interlace Plane",
      :thumb => "-quality 80 -interlace Plane"
    },
    :s3_headers => { 'Cache-Control' => 'max-age=315576000', 'Expires' => 10.years.from_now.httpdate }
    }.merge(PAPERCLIP_STORAGE_OPTIONS)

PS: Make sure you reprocess all the attachments :)