Reputation: 118
I am currently building a rails application and trying to improve its page speed insight mark. The only remaining warning would be my assets headers.
After looking at rails documentation and some articles on the internet, here's what I came up with in my production.rb file:
config.public_file_server.headers = {
'Cache-Control' => 'public, s-maxage=31536000, max-age=86400',
'Expires' => "#{1.day.from_now.httpdate}"
}
Now, here's what appears in my chrome network tab for my js/css file:
cache-control:public, max-age=86400
content-encoding:gzip
content-length:90444
content-type:application/javascript
date:Tue, 22 Aug 2017 10:49:05 GMT
last-modified:Tue, 22 Aug 2017 08:49:06 GMT
server:...
The cache-control appears as it should but there's no expires header.
I also use cloudfront on top of that but I'm not sure I should/can alter the headers from there.
Am I doing it wrong?
Upvotes: 4
Views: 1774
Reputation: 392
If you are using Rails 4, then only Cache-Control
response header can be set for assets served by Rails. That’s a limitation.
Your solution is working for Rails 5
There is a test in Rails 5 source code, which ensures that custom header is included in response:
def test_serves_files_with_headers
headers = {
"Access-Control-Allow-Origin" => "http://rubyonrails.org",
"Cache-Control" => "public, max-age=60",
"X-Custom-Header" => "I'm a teapot"
}
app = ActionDispatch::Static.new(DummyApp, @root, headers: headers)
response = Rack::MockRequest.new(app).request("GET", "/foo/bar.html")
assert_equal "http://rubyonrails.org", response.headers["Access-Control-Allow-Origin"]
assert_equal "public, max-age=60", response.headers["Cache-Control"]
assert_equal "I'm a teapot", response.headers["X-Custom-Header"]
end
Also, even if you add Expires
header somehow, max-age
will take precedence anyway.
Upvotes: 4
Reputation: 11876
config.public_file_server.headers = {
'Cache-Control' => 'public, s-maxage=31536000, max-age=86400',
'Expires' => "#{1.day.from_now.to_formatted_s(:rfc822)}"
}
try this
Upvotes: 1