[英]How to enable output compression (gzip) on everything that goes out of my Ruby on rails on Mongrel/WEBrick Server?
[英]How to enable compression in Ruby on Rails?
我在這里發布了一個類似的問題
使用 Rack-Zippy 在 Heroku 中提供壓縮資產
但決定放棄該服務,因為我無法讓它工作。
我在我的網站上運行 PageSpeed Insights 來確定我網站的速度。
我收到的最重要的建議是啟用壓縮。
Compressing resources with gzip or deflate can reduce the number of bytes sent over the network.
Enable compression for the following resources to reduce their transfer size by 191.2KiB
(74% reduction).
我已按照本網站上的說明進行操作
https://developers.google.com/speed/docs/insights/EnableCompression
它說要查閱有關如何啟用壓縮的 Web 服務器的文檔:
我已經使用這個網站來找出我的網絡服務器
http://browserspy.dk/webserver.php
原來我的網絡服務器是WEBrick。
PageSpeed Insights 頁面僅列出以下 3 個服務器
Apache: Use mod_deflate
Nginx: Use ngx_http_gzip_module
IIS: Configure HTTP Compression
我搜索了有關 WEBrick 服務器的 gzip 壓縮的文檔,但找不到任何內容。
我搜索了如何在 Rails 中啟用壓縮,但找不到任何東西。 這就是我在這里問的原因。
我試過使用 Rack Zippy 但放棄了。
現在,我什至不知道從哪里開始。 我的第一步,是找出我應該做什么。
編輯
我遵循了 Ahmed 的使用 Rack::Deflator 的建議
我通過運行確認我擁有它
rake middleware
=> use Rack::Deflator
進而
git add .
git commit -m '-'
git push heroku master
不幸的是,PageSpeed 仍然說它需要壓縮。 我通過進入開發人員工具<<網絡設置並刷新頁面來確認。 每個資源的大小和內容幾乎相同,這意味着文件沒有被壓縮。
我的一個文件有問題嗎?
感謝您的幫助。
這是我的完整 config/application.rb 文件
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module AppName
class Application < Rails::Application
config.middleware.use Rack::Deflater
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
config.exceptions_app = self.routes
config.cache_store = :memory_store
end
end
如果有問題,應該是源頭在那邊吧?
我需要安裝 deflator gem 嗎?
啟用壓縮
將其添加到 config/application.rb:
module YourApp
class Application < Rails::Application
config.middleware.use Rack::Deflater
end
end
來源: http : //robots.thoughtbot.com/content-compression-with-rack-deflater
如果您使用insert_before
(而不是“use”), Rack::Deflater
應該可以工作,將其放置在中間件堆棧的頂部附近,在任何其他可能發送響應的中間件之前。 .use
將它放在堆棧的底部。 在我的機器上,最頂層的中間件是Rack::Sendfile
。 所以我會使用:
config.middleware.insert_before(Rack::Sendfile, Rack::Deflater)
您可以通過從命令行執行rake middleware
來按加載順序獲取中間件列表。
根據Rack::Deflater
的作者,它應該放在 Rails 應用程序中的ActionDispatch::Static
之后。 理由是,如果您的應用程序還提供靜態資產(例如在 Heroku 上),那么當資產從磁盤提供時,它們已經被壓縮。 之前插入它只會導致Rack::Deflater
嘗試重新壓縮這些資產。 因此作為性能優化:
# application.rb
config.middleware.insert_after ActionDispatch::Static, Rack::Deflater
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.