【问题标题】:How to enable gzip compression for static Rack sites on Heroku Cedar?如何为 Heroku Cedar 上的静态 Rack 站点启用 gzip 压缩?
【发布时间】:2013-02-17 21:01:52
【问题描述】:

Creating Static Sites in Ruby with Rack 文章之后,我在 Heroku 上获得了一个静态站点,其 config.ru 如下所示:

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

【问题讨论】:

    标签: heroku gzip rack deflate cedar


    【解决方案1】:

    从我的 previous experience 与 Sprockets、Sinatra 和 Rack::Deflater 来看,我很确定我只是另一个 use Rack::Deflater 行,远离我想要的。

    我把config.ru改成了这样:

    use Rack::Static,
      :urls => ["/images", "/js", "/css"],
      :root => "public"
    use Rack::Deflater
    
    run lambda # ...same as in the question
    

    并且我能够验证响应是压缩发送的:

    $ 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 有效(注意use Rack::Deflater 现在在use 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多