CONTEXT:

There are many ways you can optimize your website’s page load speed. If you would like to check how else you should optimize your site, you may check out Google’s Page Speed Tool. One way is through serving compressed assets. If you happen to use SVG files, you may compress them first through gzip.

If you want to use compressed svg files (image.svg.gz ), and you want to let AWS S3 serve it as the original svg, make sure your metadata has the following key-value pairs:

Content-Encoding : gzip
Content-Type : image/svg+xml

This setting can be done through the Properties tab of your uploaded file within S3 dashboard.


PROBLEM:

If you upload your image.svg.gz file to S3 using Carrierwave, the file will have application/x-gzip as its Content-Type, and will have nothing for Content-Encoding.


SOLUTION:

My solution was to modify the uploader to override both values. CarrierWave::MimeTypes had a helper set_content_type, but it’s been deprecated. I based my code on the solution here

class ImageUploader < CarrierWave::Uploader

  storage :fog
  process :set_content_type

  # some code here

  def set_content_type
    if file.try(:content_type) == 'application/x-gzip'
      file.content_type = 'image/svg+xml'
    end
  end

  # This can also be done in the config file

  def fog_attributes
    file.extension == 'gz' ? {content_encoding: 'gzip'} : {}
  end
end

For more config options for fog-aws, refer to their readme. Finally, when you upload your compressed svg file, S3 will serve the original svg file.