2013-03-03 53 views
4

Creating Static Sites in Ruby with Rack文章中,我得到在Heroku上的靜態網站與config.ru,看起來像這樣:如何在Heroku Cedar上爲靜態Rack網站啓用gzip壓縮?

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

回答

8

從我的previous experience與鏈輪,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 

,我能驗證迴應被送往gzip壓縮:

$ 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 

這就是當我意識到這是一個標準的中間件堆棧 - 機架::靜態intercepts對靜態文件的調用,從而跳過下面的堆棧!這就是爲什麼它適用於public/index.html但不適用於資產。

以下config.ru工作(注意,現在use Rack::Deflateruse 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