Add Expires Headers in Rails

"Expires headers tell the browser whether they should request a specific file from the server or whether they should grab it from the browser's cache." gtmetrix.com

 

 

Add Rack Deflater To config.ru and Change Your config.ru From This :

 

 

[code language="ruby"] # This file is used by Rack-based servers to start the application. require ::File.expandpath('../config/environment', _FILE) run AppName::Application [/code]

 

Into this :

 

 

[code language="ruby"] # This file is used by Rack-based servers to start the application. require ::File.expandpath('../config/environment', _FILE) use Rack::Deflater run AppName::Application [/code]

 

 

Configure Your production.rb File Make Sure You Add or Uncomment This Config in Your production.rb File :

 

 

[code language="ruby"] config.serve_static_assets = true config.static_cache_control = "public, max-age=31536000" [/code]

 

Use asset_path/image_tag to load your asset You have to make sure that you use asset_path/image_tag to load your asset or expires header will not added to your asset. Avoid use naked html to load your image, so that with your CSS or JavaScript files. You can use asset_path in your CSS or JavaScript files, just change your CSS files into .css.erb and your JavaScript files to .js.erb so you can use asset_path to load your asset. See the example below :

 

 

[code language="ruby"] $( ".datepicker" ).datepicker({ buttonImage: "<%= asset_path('dtIcon.png') %>", buttonImageOnly: true, dateFormat: 'd MM yy'}); #container { background:url(<%= asset_path 'close.png' %>) no-repeat; border: none; } [/code]

 

 

You Can Use Your Browser Developer Tool to See That Your Assets Already Added Expires Header or Not.

expires-headers-in-rails

 

Mostly expires header used on static image asset, but they can and should be used on all page components including scripts, style sheets and flash.

 

 

Written by : Aditia Mahdar - Web Developer at 41studio


Ruby On Rails Blog and Web Development | 41studio

By Admin on December 07, 2013