在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
?
答案 0 :(得分:10)
来自我的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
我能够验证响应是否已发送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
有效(请注意,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