Add Expires header to rails assets - ruby-on-rails

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?

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.

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

Related

Setting public_file_server.headers except for some files

I use this in production.rb :
config.public_file_server.headers = {
'Cache-Control' => 'public, s-maxage=31536000, maxage=31536000',
'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}
I use public files through a cdn.mydomain.com, which is reading from www.mydomain.com and it copies the cache-control from www.mydomain.com, that I set with public_file_server.headers.
The issue is that I want some files from /public to not have those cache-control, for example for my service-worker.js
Is there a way to set those cache control only for one folder in /public for example?
The other solution would be to remove this public_file_server.headers configuration, and setting the cache control on the cdn level (I use cdn.mydomain.com/publicfile), and keeping www.mydomain.com/serviceworker without cache control, for the service worker.
But maybe there is a chance to config this at the Rails level?
I had exactly the same problem: PWA built with Rails using CDN (Cloudfront). For the assets I want to use cache headers with far future expires, but the ServiceWorker needs Cache-control: No-cache.
Because CloudFront doesn't allow to add or change headers by itself, I need a solution on the app level. After some research I found a solution in a blogpost. The idea is to set headers via public_file_server.headers and add a middleware to change this for the ServiceWorker file.
Also, you wrote maxage=, it should be max-age=.
Here is the code I use:
production.rb:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.public_file_server.headers = {
'Cache-Control' => 'public, s-maxage=31536000, max-age=15552000',
'Expires' => 1.year.from_now.to_formatted_s(:rfc822)
}
if ENV['RAILS_SERVE_STATIC_FILES'].present?
config.middleware.insert_before ActionDispatch::Static, ServiceWorkerManager, ['sw.js']
end
app/middleware/service_worker_manager.rb:
# Taken from https://codeburst.io/service-workers-rails-middleware-841d0194144d
#
class ServiceWorkerManager
# We’ll pass 'service_workers' when we register this middleware.
def initialize(app, service_workers)
#app = app
#service_workers = service_workers
end
def call(env)
# Let the next middleware classes & app do their thing first…
status, headers, response = #app.call(env)
dont_cache = #service_workers.any? { |worker_name| env['REQUEST_PATH'].include?(worker_name) }
# …and modify the response if a service worker was fetched.
if dont_cache
headers['Cache-Control'] = 'no-cache'
headers.except!('Expires')
end
[status, headers, response]
end
end

Rails 5 cache control doesn't work in heroku

I am setting up the CDN in my application, and by setting the cache-control according to the new standards in Rails 5:
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age = 31536000',
    'Expires' => "# {1.year.from_now.to_formatted_s (: rfc822)}"
}
But when I'm deploying the application to Heroku, it indicates that I am not using the new standards:
DEPRECATION WARNING: config.static_cache_control is deprecated and will be removed in Rails 5.1.
Please use config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=604800' } instead.
(called from at /app/config/application.rb:14)
And when I view the page response headers not being applied cache-control to set
Is that comma between the hash values only missing in this question, or also in your configuration? Try this:
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age = 31536000',
'Expires' => "# {1.year.from_now.to_formatted_s (: rfc822)}"
}
I found the solution on this issue https://github.com/romanbsd/heroku-deflater/issues/26, the problem was with the gem heroku deflater

Rails 3.2 Rack::Cache HTTP Headers and Action Caching

Good afternoon,
I've run into some issues trying to combine HTTP caching with Rack::Cache and action caching (on my Heroku-hosted app).
Using them individually, it seems to be working. With action caching enabled, the page loading is snappy, and the log would suggest it is caching. With HTTP caching in the controllers (eTag, last_modified and fresh_when) the proper headers appear to be set.
However, when I try to combine the two, it appears to be action caching, but the HTTP headers are always max_age: 0, must_revalidate. Why is this? Am I doing something wrong?
For example, here's the code in my "home" action:
class StaticPagesController < ApplicationController
layout 'public'
caches_action :about, :contact, ......, :home, .....
......
def home
last_modified = File.mtime("#{Rails.root}/app/views/static_pages/home.html.haml")
fresh_when last_modified: last_modified , public: true, etag: last_modified
expires_in 10.seconds, :public => true
end
For all intents and purposes, this should have a public cache-control tag with max-age 10 no?
$ curl -I http://myapp-staging.herokuapp.com/
HTTP/1.1 200 OK
Cache-Control: max-age=0, private, must-revalidate
Content-Type: text/html; charset=utf-8
Date: Thu, 24 May 2012 06:50:45 GMT
Etag: "997dacac05aa4c73f5a6861c9f5a9db0"
Status: 200 OK
Vary: Accept-Encoding
X-Rack-Cache: stale, invalid
X-Request-Id: 078d86423f234da1ac41b418825618c2
X-Runtime: 0.005902
X-Ua-Compatible: IE=Edge,chrome=1
Connection: keep-alive
Config Info:
# Use a different cache store in production
config.cache_store = :dalli_store
config.action_dispatch.rack_cache = {
:verbose => true,
:metastore => "memcached://#{ENV['MEMCACHE_SERVERS']}",
:entitystore => "memcached://#{ENV['MEMCACHE_SERVERS']}"#,
}
In my mind, you should be able to use action caching as well as a reverse proxy correct? I know that they do fairly similar things (if the page changes, both the proxy and the action cache will be invalid and need to be regenerated), but I feel I should be able to have both in there. Or should I get rid of one?
UPDATE
Thanks for the answer below! It seems to work. But to avoid having to write set_XXX_cache_header methods for every controller action, do you see any reason why this wouldn't work?
before_filter :set_http_cache_headers
.....
def set_http_cache_headers
expires_in 10.seconds, :public => true
last_modified = File.mtime("#{Rails.root}/app/views/static_pages/#{params[:action]}.html.haml")
fresh_when last_modified: last_modified , public: true, etag: last_modified
end
When you use action caching, only the response body and content type is cached. Any other changes to the response will not happen on subsequent requests.
However, action caching will run any before filters even when the action itself is cached.
So, you can do something like this:
class StaticPagesController < ApplicationController
layout 'public'
before_filter :set_home_cache_headers, :only => [:home]
caches_action :about, :contact, ......, :home, .....
......
def set_home_cache_headers
last_modified = File.mtime("#{Rails.root}/app/views/static_pages/home.html.haml")
fresh_when last_modified: last_modified , public: true, etag: last_modified
expires_in 10.seconds, public: true
end

How to STOP caches_page from setting page in cache permanently? -- Rails 3.1

I want to make sure that if the file changes (if cache files are deleted for example), the user's browser shouldn't load the cached version.
Here is the issue I found. Here are the headers when I DON'T use caches_page:
HTTP/1.1 200 OK =>
ETag => "4ff902bc57e1892d7a963e43bf56dcc8"
X-UA-Compatible => IE=Edge,chrome=1
Cache-Control => max-age=0, private, must-revalidate
X-Runtime => 2.710376
X-Rack-Cache => miss
Set-Cookie => _Myapp_session=.....; path=/; HttpOnly
Status => 200
And here are the headers when I do use it:
HTTP/1.1 200 OK =>
ETag => "80003-1ad93-4b44a71a41180"
Last-Modified => Sat, 17 Dec 2011 14:22:14 GMT
Accept-Ranges => bytes
I've removed the common lines for easy comparison.
Are there any issues with these differing headers?
I didn't find any rails way to do this so put in "Header set" directives in apache.conf

How do I set Expires: header when using send_data

I have a method in my controller which uses send_data like this:
def show
expires_in 10.hours, :public => true
send_data my_image_generator, :filename => "image.gif", :type => "image/gif"
end
Using expires_in results in headers being sent like this:
HTTP/1.1 200 OK
Connection: close
Date: Fri, 25 Jun 2010 10:41:22 GMT
ETag: "885d75258e9306c46a5dbfe3de44e581"
Content-Transfer-Encoding: binary
X-Runtime: 143
Content-Type: image/gif
Content-Disposition: inline; filename="image.gif"
Content-Length: 1277
Cache-Control: max-age=36000, public
What I would like to do is add an header like Expires: (some exact date) to keep the user agent from revalidating. But I don't see how to make send_data set that header?
I guess I could set it explicitly in the response.headers hash, but surely there must be a wrapper for that (or something)?
I came across this syntax and I like it :-)
response.headers["Expires"] = 1.year.from_now.httpdate
Apparently there seems to be no way to pass expires to send_data - instead you must set it yourself in response.headers and take care of formatting the date appropriately:
response.headers["Expires"] = CGI.rfc1123_date(Time.now + period)
Note that the max-age directive in the Cache-Control header overrides the Expires header if both are present. See RFC2616 Section 14.9.3 for more details.
The code in your question should actually work on recent Rails:
`expires_in 10.hours, :public => true`

Resources