Rails 4: assets not loading in production

前端 未结 18 1435
梦如初夏
梦如初夏 2020-11-29 15:15

I\'m trying to put my app into production and image and css asset paths aren\'t working.

Here\'s what I\'m currently doing:

  • Image assets live in /app/a
18条回答
  •  时光说笑
    2020-11-29 16:09

    There are 2 things you must accomplish to serve the assets in production:

    1. Precompile the assets.
    2. Serve the assets on the server to browser.

    1) In order to precompile the assets, you have several choices.

    • You can run rake assets:precompile on your local machine, commit it to source code control (git), then run the deployment program, for example capistrano. This is not a good way to commit precompiled assets to SCM.

    • You can write a rake task that run RAILS_ENV=production rake assets:precompile on the target servers each time you deploy your Rails app to production, before you restart the server.

    Code in a task for capistrano will look similar to this:

    on roles(:app) do
      if DEPLOY_ENV == 'production'
        execute("cd #{DEPLOY_TO_DIR}/current && RAILS_ENV=production rvm #{ruby_string} do rake assets:precompile")
      end
    end
    

    2) Now, you have the assets on production servers, you need to serve them to browser.

    Again, you have several choices.

    • Turn on Rails static file serving in config/environments/production.rb

      config.serve_static_assets = true # old
      
      or
      
      config.serve_static_files = true # new
      

      Using Rails to serve static files will kill your Rails app performance.

    • Configure nginx (or Apache) to serve static files.

      For example, my nginx that was configured to work with Puma looks like this:

      location ~ ^/(assets|images|fonts)/(.*)$ {
          alias /var/www/foster_care/current/public/$1/$2;
          gzip on;
          expires max;
          add_header Cache-Control public;
      }
      

提交回复
热议问题