I have a cedar application that uses Rails 4.0 and the asset pipeline. I'd like to set custom headers for all assets from the asset pipeline. How can this be done?
Asked
Active
Viewed 821 times
4
-
Which kind of header? – Oz Ben-David Jul 18 '13 at 16:01
2 Answers
4
An easy way would be to use a rack plugin, something like this:
class RackAssetFilter
def initialize app
@app = app
end
def call env
@status, @headers, @body = @app.call env
if env['PATH_INFO'].starts_with?( "/assets/" )
@headers['X-Header-1'] = 'value'
# ...
end
return [@status, @headers, @body]
end
end
To enable it, in application.rb:
config.middleware.insert_before( ActionDispatch::Static, RackAssetFilter )
Keep in mind you need to declare or load the RackAssetFilter via require before you insert it into the middleware stack in application.rb
2
Since Rails 5 you can use the config public_file_server.headers
in the configuration file of the corresponding environment that you want to apply the desired headers, for example:
# in config/environments/production.rb
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=31536000"
}
The above snippet will configure the Cache-Control
header with public, max-age=31536000
value for you assets in the production environment. You can also set any custom headers.

Oscar Rivas
- 88
- 1
- 8