Search code examples
ruby-on-railsnginxassetsunicorn

Nginx: Configure nginix for serving non precompiled assets in production


I have a rails app with locomotive cms. I want to be able to reference specific css/js files through my CMS and have been able to in development using a URL like assets/subfolder/file.css. When I deployed my app to a server using nginx and unicorn those URLs no longer worked and all my images stopped loading. After adding the following to my nginx conf file images started loading but CSS/JS files still do not work.

root /var/www/myproject/public/;
location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;

  add_header ETag "";
  break;
}    

What do I need to configure so that nginix and unicorn can serve assets from the app/assets/css or app/assets/javascript directories?


Solution

  • Hopefully, there's a good reason you don't want to precompile assets, but this should help.

    #{Rails.root}/config/environments/production.rb
    config.serve_static_assets = true
    

    By default, Rails apps will not serve assets when Rails.env == "production". In dev/test environments, Rails will handle the request to assets/subfolder/file.css and correctly render assets out of #{Rails.root}/app/assets/subfolder/file.css.

    rake assets:precompile places the resulting css/js files in #{Rails.root}/public/assets which will resolve correctly relative to the root location in your nginx config.

    With expires 1y; in your nginx config, any changes to the referenced css/js files may not be requested by browsers that have a cached copy.