I'm using the latest Sinatra and I'm hosting on Heroku. Is there a way I can set the caching headers for my static assets served from the /public
directory?
Sinatra serves files from the /public
directory before checking any routes that have been defined, so I can’t just the cache_control
method inside a route.
The /public
directory contains the CSS and JavaScript of my app. I don’t want the browser to download those files every single time, since they won't change often.
You can use the static_cache_control
setting to set the Cache-Control
header for static files served by Sinatra:
set :static_cache_control, [:public, max_age: 60 * 60 * 24 * 365]
Note you need to use an explicit array [...]
.
Also this will apply to all files in the public
directory, i.e. you can’t specify different headers for css and javascript files.
(If you’re not using Heroku and are using Apache or Nginx to serve static files then this won’t work, in that case you’d need to configure your webserver separately).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With