Last active
August 29, 2015 14:21
-
-
Save amw/011f0b1dca8d05d50a7c to your computer and use it in GitHub Desktop.
Preparing compressed (gzipped) Rails assets for Nginx mod_gzip_static
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/tasks/assets.rake | |
namespace :assets do | |
ManifestPattern = /^manifest-[0-9a-f]{32}\.json$/ | |
ExtensionsToCompress = %w{.js .css .json}.freeze | |
desc "GZip assets" | |
task :compress do | |
files = Pathname.glob(Rails.root.join('public/assets/**/*')).map do |file| | |
next unless file.extname.in? ExtensionsToCompress | |
next if file.basename.to_s =~ ManifestPattern | |
gzipped = file.to_s + ".gz" | |
next if File.exist? gzipped | |
[file, gzipped] | |
end.compact | |
start = -> item, index { | |
gzipped = item.last | |
puts "Creating #{gzipped}" | |
} | |
Parallel.each files, start: start do |file,gzipped| | |
Zlib::GzipWriter.open gzipped, Zlib::BEST_COMPRESSION do |dest_io| | |
open file, "rb" do |source_io| | |
dest_io << source_io.read(16384) until source_io.eof? | |
end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/capistrano/tasks/assets.rake | |
namespace :deploy do | |
desc "Gzip assets" | |
task :compress_assets do | |
on roles(fetch(:assets_roles)) do | |
within release_path do | |
with rails_env: fetch(:rails_env) do | |
execute :rake, "assets:compress" | |
end | |
end | |
end | |
end | |
end | |
after "deploy:compile_assets", "deploy:compress_assets" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
# ... | |
location ~* ^/assets/ { | |
gzip_static on; | |
expires max; | |
add_header Cache-Control public; | |
add_header Last-Modified ""; | |
add_header ETag ""; | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment