Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.2 App Not Serving Gzipped Assets

I am trying to optimise my rails 4 application by serving GZipped assets instead of regular compiled assets. GZip compression is described in section 4.1.2 of this Rails guide: http://guides.rubyonrails.org/asset_pipeline.html

The rails asset pipeline has indeed produced gzipped versions of my assets after pre-compiling them, and I can see these on my server's filesystem in my app's public folder.

However, my webpages fall back to serving the un-compressed assets instead of the gzipped version when inspecting the network activity. This had lead me to think that my web server is not configured correctly to serve the gzipped assets. I'm using NGINX and the passenger module in-front of my rails app.

I've firstly tried using the recommended NGINX configuration in the Rails Asset Pipeline guide by adding the following to my config file:

location ~ ^/(assets)/  {
  root /path/to/public;
  gzip_static on; # to serve pre-gzipped version
  expires max;
  add_header Cache-Control public;
}

I then double checked that the http_gzip_static_module was indeed compiled with my NGINX installation:

/opt/nginx/sbin/nginx -V    # --with-http_gzip_static_module

With the NGINX config updated, and confirmation that http_gzip_static_module is in my installation, I then played about with the config.serve_static_files option in my production.rb file:

config.serve_static_files = true
config.serve_static_files = false
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

These three settings all resulted in my server falling back to the regular compressed assets.

Lastly, I tried installing the rack-zippy gem (https://github.com/eliotsykes/rack-zippy) - which prioritises serving the static gzipped assets and falls back to the regular compressed assets otherwise. This also didn't work, which probably means my NGINX configuration needs amending.

Any help much appreciated!

like image 462
weasel Avatar asked Apr 07 '15 21:04

weasel


Video Answer


1 Answers

This answer solved it for me: https://stackoverflow.com/a/40824720/667335

I was missing this in config/production.rb

config.middleware.insert_before(Rack::Sendfile, Rack::Deflater)

# Compress JavaScripts and CSS.
config.assets.compress = true
config.assets.js_compressor = Uglifier.new(mangle: false)
like image 197
Allen Avatar answered Nov 22 '22 10:11

Allen