11

I'm using the latest Sinatra and I'm hosting on Heroku. Is there a way I can set the caching headers for my static assets served from the /public directory?

Sinatra serves files from the /public directory before checking any routes that have been defined, so I can’t just the cache_control method inside a route.

The /public directory contains the CSS and JavaScript of my app. I don’t want the browser to download those files every single time, since they won't change often.

4

2 に答える 2

15

You can use the static_cache_control setting to set the Cache-Control header for static files served by Sinatra:

set :static_cache_control, [:public, max_age: 60 * 60 * 24 * 365]

Note you need to use an explicit array [...].

Also this will apply to all files in the public directory, i.e. you can’t specify different headers for css and javascript files.

(If you’re not using Heroku and are using Apache or Nginx to serve static files then this won’t work, in that case you’d need to configure your webserver separately).

于 2012-10-10T21:51:17.133 に答える
1

I created a simple Sinatra site using:

#!/usr/bin/env ruby

require 'sinatra'

get '/public/*' do
  cache_control :public, max_age: 60 * 60 * 24 * 365
  'this is public'
end

get '/' do
    'hello world!'
end

When I requested '/', I got these headers:

x-frame-options: sameorigin
x-xss-protection: 1; mode=block
Content-Type: text/html;charset=utf-8
Content-Length: 12
Connection: keep-alive
Server: thin 1.5.0 codename Knife

200 OK

When I requested '/public/foo', I got these:

x-frame-options: sameorigin
x-xss-protection: 1; mode=block
Content-Type: text/html;charset=utf-8
Cache-Control: public, max-age=31536000
Content-Length: 14
Server: thin 1.5.0 codename Knife

200 OK

It's working on a current Sinatra (1.3.3) on Ruby 1.9.3p194.

于 2012-10-10T19:38:00.613 に答える