【问题标题】:Caching a redirect to a static image in Sinatra在 Sinatra 中缓存到静态图像的重定向
【发布时间】:2015-07-09 08:53:33
【问题描述】:

我有一个用于显示状态图像的 Sinatra 路由。虽然这个简单的解决方案有效,但我遇到了缓存问题:

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

  redirect image_url
end

在此处处理缓存以设置最大 TTL 的正确方法是什么?这些图像将嵌入其他网站,否则我可以直接链接到我重定向到的图像。

问题在于它会生成一个类似 site.com/image.png 的 URL,而该 URL 又会重定向到其他地方 - 但它是 site.com/image.png 被浏览器视为缓存,因此它不会检查它是否已更新。

我已经对 Cache-Control 标头进行了一些试验,但我还没有找到解决方案。

如果这种方法完全愚蠢,我愿意接受其他解决方案。

【问题讨论】:

    标签: ruby caching sinatra cache-control


    【解决方案1】:

    您在每个路由的基础上设置缓存控制:

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

    【讨论】:

      【解决方案2】:

      你也可以使用 Sinatra 的expires 方法:

      # Set the Expires header and Cache-Control/max-age directive. Amount
      # can be an integer number of seconds in the future or a Time object
      # indicating when the response should be considered "stale". The remaining
      # "values" arguments are passed to the #cache_control helper:
      #
      #   expires 500, :public, :must_revalidate
      #   => Cache-Control: public, must-revalidate, max-age=60
      #   => Expires: Mon, 08 Jun 2009 08:50:17 GMT
      

      或者cache_control方法:

      # Specify response freshness policy for HTTP caches (Cache-Control header).
      # Any number of non-value directives (:public, :private, :no_cache,
      # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
      # a Hash of value directives (:max_age, :min_stale, :s_max_age).
      #
      #   cache_control :public, :must_revalidate, :max_age => 60
      #   => Cache-Control: public, must-revalidate, max-age=60
      #
      # See RFC 2616 / 14.9 for more on standard cache control directives:
      # http://tools.ietf.org/html/rfc2616#section-14.9.1
      

      Sinatra 文档(截至 1.4.6 版)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-13
        • 2017-08-21
        • 2016-03-30
        • 2015-06-26
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多