Search code examples
rubycachingsinatracache-control

Caching a redirect to a static image in Sinatra


I have a Sinatra route for displaying a status image. While this simple solution works, I run into caching issues:

get '/stream/:service/:stream_id.png' do
  # Building image_url omitted

  redirect image_url
end

What is a proper way to handle the caching here, to set a max TTL? These images will be embedded on other sites, otherwise I could simply link straight to the images I redirect to.

The problem is that it generates an URL like site.com/image.png which in turn redirects elsewhere -- but it's site.com/image.png that is considered cached by the browser, so it won't check if it's updated.

I've experimented a bit with Cache-Control headers, but I have yet to find a solution.

I'm open for other solutions if this method is completely boneheaded.


Solution

  • You set the Cache-Control on a per route basis:

    get '/stream/:service/:stream_id.png' do
      # Building image_url omitted
      response['Cache-Control'] = "public, max-age=0, must-revalidate"
      redirect image_url
    end