【问题标题】:Configure nginx to serve cached images配置 nginx 以提供缓存的图像
【发布时间】:2010-12-08 22:21:54
【问题描述】:

我有一个生成大量图像的 Rails 应用程序;即,具有显示操作的图像控制器从 SAN 中获取图像并为其提供服务。我有一个 caches_page ,它可靠地将文件的副本保存在自定义位置; RAILS_ROOT + /公共/缓存。文件在那里,看起来不错。

我正在通过 nginx 为应用程序提供服务,它似乎工作正常,但在我的一生中,我无法让它发送那些缓存的图像文件,而不是点击 rails 操作。我对 nginx 很陌生,并且已经研究了一段时间,但无论我尝试什么它都不起作用 - 我做的事情根本上是错误的。

为了澄清,我有一个这样的 uri:

/images/show/123.jpg

该文件可能存在于此处:

/cache/images/show/123.jpg

如何让 nginx 服务该文件而不传递请求?

这是我尝试过的不完整列表:

if (-f /cache$request_filename) { 
  rewrite (.*) /cache$1 break;
  break; 
}

if (-f /cache$uri.jpg) {
rewrite (.*) /cache$1.jpg break;
}

if (-f /cache/images/show/$request_filename) {
rewrite (.*) /cache/images/show/$1.jpg break;
}

有什么想法吗?

更新:我回答了我自己的问题。正确的规则是:

      if (-f $document_root/cache$request_uri) {
      rewrite (.*) /cache$1 break;
      }

【问题讨论】:

标签: nginx


【解决方案1】:

您也可以使用 MemcachedModule 直接在 Nginx 上缓存图像。

【讨论】:

    【解决方案2】:

    nginx 的推荐方式是使用 the "try_files" directive

    类似

    location /images/show {
        root ...;
        try_files $document_root/cache$uri /fromrootpath/$uri;
    }
    

    【讨论】:

    • try_files 是一个很好的方法(比 if 语句更好。)但我认为该指令应该是 try_files $document_root/cache$uri $uri; 因此如果找不到缓存的图像,它会回退到请求的 uir。跨度>
    • @myanimal 确定,已修复
    猜你喜欢
    • 2021-05-08
    • 2019-01-24
    • 2011-02-21
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多