Heroku

How It Works
Marshall Huss

This article was contributed by Marshall Huss

Co-founder of TwoGuys where he does Ruby on Rails and iOS development. Marshall is also the creator of Nezumi, the iOS app for Heroku.

Static Sites with Ruby on Heroku/Bamboo

Last Updated: 26 January 2012

bamboo

Sometimes you just have a static website with one or two pages. Here is a simple way to host your static site and cache it on Heroku using a Rack app.

Your folder should be organized like this:

- MySite
  |- config.ru
  |- public
    |- index.html
    |- stylesheets
    |- images

In config.ru file add the following:

use Rack::Static, 
  :urls => ["/stylesheets", "/images"],
  :root => "public"

run lambda { |env|
  [
    200, 
    {
      'Content-Type'  => 'text/html', 
      'Cache-Control' => 'public, max-age=86400' 
    },
    File.open('public/index.html', File::RDONLY)
  ]
}

This assumes that your template uses relative references to the images and stylesheets. Go ahead and deploy the app. If you are not sure how to deploy to Heroku check out the quickstart guide.

All Heroku apps are fronted by Varnish, an HTTP Accelerator, and we should take advantage of it. You may have noticed in the config.ru file we set the Cache-Control header to 86400 seconds (24 hours). This tells the accelerator to go ahead and cache the page. The accelerator already caches any Rack::File for 12 hours as well meaning all your stylesheets and images will also be cached.

To confirm it’s working, let’s take a look at the HTTP headers returned from your site. The Age header indicates that it’s being served from the HTTP cache.

$ curl -I http://nezumiapp.com/                        
HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Sat, 30 Apr 2011 02:26:12 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
X-Runtime: 29
ETag: "a90d1cf7a727aee09abfc7df23bc0b71"
Cache-Control: public, max-age=86400
Content-Length: 3400
X-Varnish: 695131796 695100190
Age: 98
Via: 1.1 varnish

And there you go, a static site being served on Heroku completely cached and easily served using a single dyno.