如何在Heroku Cedar上为静态Rack站点启用gzip压缩?

Creating Static Sites in Ruby with Rack文章之后,我在Heroku上获得了一个静态网站,其配置如下:

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

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

当我在结果上运行YSlow时,它报告没有文件被gzip压缩.如何压缩资产和public / index.html?

最佳答案
从我的带有Sprockets,Sinatra和Rack :: Deflater的previous experience开始,我非常确定我只是使用了Rack :: Deflater,而不是我想要的东西.

我将config.ru更改为:

use Rack::Static,
  :urls => ["/images", "/js", "/css"],
  :root => "public"
use Rack::Deflater

run lambda # ...same as in the question

我能够验证响应是否被gzipped发送:

$curl -H 'Accept-Encoding: gzip' http://localhost:9292 | file -
/dev/stdin: gzip compressed data

但不适用于/ css,/ js或/ images下的静态资产:

$curl -H 'Accept-Encoding: gzip' http://localhost:9292/css/bootstrap.min.css | file -
/dev/stdin: ASCII English text, with very long lines

那时我意识到这是一个标准的中间件堆栈 – Rack :: Static intercepts对静态文件的调用,从而跳过下面的堆栈!这就是为什么它适用于public / index.html但不适用于资产.

以下config.ru工作(注意使用Rack :: Deflater现在先使用Rack :: Static):

use Rack::Deflater
use Rack::Static, 
  :urls => ["/images", "/js", "/css"],
  :root => "public"

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

验证:

$curl -H 'Accept-Encoding: gzip' http://localhost:9292/css/bootstrap.min.css | file -
/dev/stdin: gzip compressed data, from Unix

转载注明原文:如何在Heroku Cedar上为静态Rack站点启用gzip压缩? - 代码日志