Reputation: 1501
I have a simple Rails 6 app with ActiveStorage. I use local disk storage. When I inspect responses from representation url like this
http://localhost:3000/rails/active_storage/disk/some-long-hash/IMG_0951.jpeg?content_type=image%2Fjpeg&disposition=inline%3B+filename%3D%22IMG_0951.jpeg%22%3B+filename%2A%3DUTF-8%27%27IMG_0951.jpeg
I see headers Cache-Control: max-age=0, private, must-revalidate
The question is how to make Rails to set public caching header with some age?
Upvotes: 10
Views: 1020
Reputation: 3632
Builinding on @anothermh's answer, here a up-2-date version for Rails 7.1 - After Zeitwerk it is difficult to call controllers or models directly from an initializer.
# config/initializers/active_storage_cache_control.rb
Rails.application.reloader.to_prepare do
ActiveStorage::DiskController.class_eval do
before_action only: [:show] do
response.set_header('Cache-Control', 'max-age=86400, public')
end
end
end
Upvotes: 1
Reputation: 10536
The #show
method for ActiveStorage::DiskController
is difficult to override but it can be done.
A simpler approach is to add an after_action
callback for the existing #show
method to insert the Cache-Control
header when it is called:
# config/initializers/active_storage.rb
require 'active_storage/current'
ActiveStorage::Current.url_options = { host: 'localhost', port: 3000 }
require 'active_storage/set_current'
require 'active_storage/base_controller'
require 'active_storage/file_server'
require 'active_storage/disk_controller'
class ActiveStorage::DiskController < ActiveStorage::BaseController
after_action do
response.set_header('Cache-Control', 'max-age=3600, public') if action_name == 'show'
end
end
Requesting an ActiveStorage URL then returns the custom Cache-Control
header value in the response:
HTTP/1.1 200 OK
Cache-Control: max-age=3600, public
...
Upvotes: 1