Hegwin.Me

The bitterest tears shed over graves are for words left unsaid and deeds left undone.

Handle Assets with Nginx Instead of Thin

Nginx部署时Assets静态文件请求的配置

When deploying a Rails project to a production environment, I met a lot of problems with assets.

For the Hegwin.me blog you're reading now, I'm using Nginx and Thin as the server for deployment. Since I don't deploy very often, I basically do it manually. During my deployment, after I execute RAILS_ENV=production bundle exec rake assets:precompile and start the server in production mode, all requests for assets (CSS, JS and images) return a 404 Not Found.

I think it's incredible, why didn't I encounter this situation when I was using Unicorn?

Under my production configuration, there is this paragraph:

# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false

Changing false to true here will also solve the problem, but it's better to use Apache or Nginx for these static files.

In the Rails Guide The Asset Pipeline it is written how to use Nginx to manage them, and you need to add This paragraph:

location ~ ^/assets/ {
  expires 1y.
  add_header Cache-Control public.

  add_header ETag "".
  break.
}

After I copied and pasted this paragraph, it still didn't work right and I continued getting 404s.

And then, after searching on the Internet, I saw that some people's solution is to add root to the location configuration to specify the public path, i.e.

location ~ ^/assets/ {
  expires 1y.
  add_header Cache-Control public.
  root /srv/blog/public.

  add_header ETag "".
  break.
}

At this point, the problem is solved.

< Back