diff options
author | Eugen Rochko <eugen@zeonfederated.com> | 2023-03-16 02:55:54 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-03-16 02:55:54 +0100 |
commit | f0e727f958cd9428b2c56a3c6a65bbbf176bfa0d (patch) | |
tree | e751fd45f4edd451c04d98163439da68bf1cc890 /lib | |
parent | be488adf711e75ab05a9b22b6241c676e5615c71 (diff) |
Add cache headers to static files served through Rails (#24120)
Diffstat (limited to 'lib')
-rw-r--r-- | lib/public_file_server_middleware.rb | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/public_file_server_middleware.rb b/lib/public_file_server_middleware.rb new file mode 100644 index 000000000..3799230a2 --- /dev/null +++ b/lib/public_file_server_middleware.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require 'action_dispatch/middleware/static' + +class PublicFileServerMiddleware + SERVICE_WORKER_TTL = 7.days.to_i + CACHE_TTL = 28.days.to_i + + def initialize(app) + @app = app + @file_handler = ActionDispatch::FileHandler.new(Rails.application.paths['public'].first) + end + + def call(env) + file = @file_handler.attempt(env) + + # If the request is not a static file, move on! + return @app.call(env) if file.nil? + + status, headers, response = file + + # Set cache headers on static files. Some paths require different cache headers + headers['Cache-Control'] = begin + request_path = env['REQUEST_PATH'] + + if request_path.start_with?('/sw.js') + "public, max-age=#{SERVICE_WORKER_TTL}, must-revalidate" + elsif request_path.start_with?(paperclip_root_url) + "public, max-age=#{CACHE_TTL}, immutable" + else + "public, max-age=#{CACHE_TTL}, must-revalidate" + end + end + + [status, headers, response] + end + + private + + def paperclip_root_url + ENV.fetch('PAPERCLIP_ROOT_URL', '/system') + end +end |