在rack中应该在哪里插入Rack::Deflater?

16

我目前有以下代码:

use Rack::Rewrite
use Rack::Cache, {:verbose=>true, :metastore=>"memcached://localhost:11211/rack-cache/meta", :entitystore=>"memcached://localhost:11211/rack-cache/body"}
use Rack::Rewrite
use Rack::Lock
use Rack::Deflater
use ActionController::Failsafe
use #<Class:0x007fb34be9ac90>
use ActionController::Session::DalliStore, #<Proc:0x007fb34bea3638@(eval):8 (lambda)>
use Rails::Rack::Metal
use ActionController::ParamsParser
use Rack::MethodOverride
use Rack::Head
use ActionController::StringCoercion
use Sass::Plugin::Rack
use Hassle
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
run ActionController::Dispatcher.new

我可能错了,但将Deflater置于顶部不是更有意义吗? 这样所有的流量都将被压缩。

谢谢帮助。

3个回答

26

最简单的方法是直接在您的 config.ru 文件中插入它:

require ::File.expand_path('../config/environment',  __FILE__)
use Rack::Deflater
run My::Application

为了确认它正在工作,请启动您的应用程序并使用curl进行测试:

curl -i --head "Accept-Encoding: gzip,deflate" http://localhost:5000

应返回标头:

Vary: Accept-Encoding
Content-Encoding: gzip

还有一个美妙的gzip响应。


7
使用选项"-I"(而不是"-i")可以让curl仅返回头部信息。 - mshafrir
3
上面的是大写字母I,不是小写字母L。 - Chris Bui
3
这是一个不好的想法,因为它会对包括图像文件在内的所有资产进行GZip压缩,而你并不希望这样做。更好的选择是使用https://gist.github.com/2152663。 - maletor
2
这个回答有用的信息 (+1),但实际上并没有回答问题 (-1),问题与在config.ru中的放置有关,以及那一行是否应该靠近顶部。如果您将这些添加到一个完美的答案中,我很乐意点赞。 (我意识到问题可能最初不同,这可能直接回答了原始形式的问题。然而,更新您的答案来匹配它将非常有用。) - iconoclast
正确的命令现在是 curl -I -H 'Accept-Encoding: gzip,deflate' http://localhost:5000 - bcackerman
显示剩余3条评论

5

我必须很早就插入它(在ActionDispatch::Static之前),像这样:

# production.rb
config.middleware.insert_before ActionDispatch::Static, Rack::Deflater

您可以使用rake middleware来确认(尽管这将检查您的开发设置)。
> rake middleware
use Rack::Deflater
use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007f8e18455e90>
use Rack::Runtime
use Rack::MethodOverride
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
use ActionDispatch::ParamsParser
use Remotipart::Middleware
use ActionDispatch::Head
use Rack::ConditionalGet
use Rack::ETag
use ActionDispatch::BestStandardsSupport
use Warden::Manager
use Rack::Mongoid::Middleware::IdentityMap
use Rack::Pjax
run MyApp::Application.routes

1
尽管如此,图片不应该被Gzip压缩根据Google PageSpeed的定义。有没有跳过这些资源上的Deflator的方法? - maletor
1
这里有一个提示:除非你将config.serve_static_assets设置为true,否则它不会起作用 ;) - santuxus
不,你不想压缩大多数二进制文件,如PDF、JPEG、PNG等。它们已经被压缩过了,所以再次压缩它们的好处很小。 - Weihang Jian

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接