Serving Rails assets with nginx
Using the Rails asset pipeline makes it safe to cache assets forever in browsers. Rails is configured for this out of the box, so you only need to ensure that you precompile assets before or during each deploy.
With that out of the way you can simply add this snippet to your nginx config to allow assets with digests in their name to be cached forever in clients:
This gives special treatment to files in /public/assets/
with a 32-character hex digest in the filename. These files are exactly the ones built by the asset pipeline, and they are allowed to be publicly cached forever, as they are guaranteed to never change their contents. With this configuration in place you can also trivially use your nginx as the origin server for a CDN.
Any static files not matching the first rule are not allowed to be cached forever and will have to be re-requested with each visit. The more you can build as digested assets, the less strain you will see on your nginx server and your bandwidth bill.
Happy caching!
Hi, I'm Laust Rud Jacobsen, an experienced webapp developer specializing in Elixir, Ruby and PostgreSQL-based solutions. You can hire me to build awesome stuff for you. If you have any questions or comments, reach out at @laustrud or privately at work@valuestream.io.