Sinatra - 通过config.ru设置缓存控制标头

eli*_*rar 3 ruby rack heroku sinatra jekyll

我目前在Heroku的Cedar堆栈上运行Octopress(基于Jekyll)站点 - 代码存在于此:https://github.com/elithrar/octopress

我想Cache-Control根据文件类型有选择地应用标头:

  • .html files的值为 public, max-age=3600
  • .css|.js|.png|.ico(等)获取值public, max-age=604800- 或者,我想将此规则应用于从/stylesheets', '/javascripts', '/imgs'目录提供的任何内容.

既没有运气又使用set :static_cache_control , [:public, :max_age => 3600]了香草语cache_control :public, :max_age => 3600.

我已设法自己设置public, max-age=3600文章(例如/2012/lazy-sundays/),但无法将标题应用于CSS/JS(例如/stylesheets/screen.css)

config.ru目前看起来像这样(更新):

require 'bundler/setup'
require 'sinatra/base'

# The project root directory
$root = ::File.dirname(__FILE__)

class SinatraStaticServer < Sinatra::Base

  get(/.+/) do
    cache_control :public, :max_age => 7200
    send_sinatra_file(request.path) {404}
  end

  not_found do
    send_sinatra_file('404.html') {"Sorry, I cannot find #{request.path}"}
    cache_control :no_cache, :max_age => 0
  end

  def send_sinatra_file(path, &missing_file_block)
    file_path = File.join(File.dirname(__FILE__), 'public',  path)
    file_path = File.join(file_path, 'index.html') unless file_path =~ /\.[a-z]+$/i  
    File.exist?(file_path) ? send_file(file_path) : missing_file_block.call
  end

end

use Rack::Deflater

run SinatraStaticServer
Run Code Online (Sandbox Code Playgroud)

rob*_*omc 5

以下是如何为静态资产设置长到期标头,以及为Heroku上的主要内容设置任意到期标头:

的Gemfile:

gem 'rack-contrib'
Run Code Online (Sandbox Code Playgroud)

config.ru:

require 'rack/contrib'

get '*.html' do |page|
  # whatever code you need to serve up your main pages
  # goes here... use Rack::File I guess.
  page
end


# Set content headers for that content...
before do
  expires 5001, :public, :must_revalidate
end


# Assets in /static/stylesheets (domain.com/stylesheets) 
# are served by Rack StaticCache, with a default 2 year expiry.

use Rack::StaticCache, :urls => ["/stylesheets"], :root => Dir.pwd + '/static'

run Sinatra::Application
Run Code Online (Sandbox Code Playgroud)

默认情况下,对于网址数组中列出的内容(静态/样式表,静态/图像等),您将获得2年到期日期.

你必须从/ public移动到/ static,否则你会不必要地使用Heroku的nginx配置(正确地应用这些设置......).

我知道你说你试图不使用Rack Contrib,但这没有任何意义.使用一个小的90行库来做这件事没有害处https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/static_cache.rb.

"正确"的方式是在可以配置nginx的环境中托管静态内容,第二种最好的方法是重命名静态文件路径,以便heroku忽略它,并使用rack static来提供带有所需标头的静态文件.

-

另外要明确的是,只需将公共文件夹重命名为其他内容即可通过路由执行此操作,并且正常的Sinatra会过期.但我会使用StaticCache,因为它不那么冗长.(真正的问题是Heroku不会让nginx与您的应用程序讨论公开请求/,我相信.)