使用 x-sendfile 通过 Rails 2.3 通过 Nginx 提供大文件 [英] Serving Large Files Through Nginx via Rails 2.3 Using x-sendfile

查看:28
本文介绍了使用 x-sendfile 通过 Rails 2.3 通过 Nginx 提供大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 Rails 2.3.2 应用程序,以 nginx 为前端,由 mongrel 提供服务,我需要通过 Rails 提供一个大型静态文件(以控制对它的访问).我希望 Rails 应用将文件传输委托给 nginx,以避免阻塞 mongrel 实例.

Let's say I have a Rails 2.3.2 application fronted by nginx and served by mongrel in which I need to serve a large static file through Rails (to control access to it). I want the Rails app to delegate the transfer of the file to nginx, to avoid blocking the mongrel instance.

可用信息似乎矛盾且不完整.这篇文章 展示了如何使用 Apache 进行操作,以及暗示它也可以用 ngninx 来完成——但没有例子.这篇文章这篇文章 展示了如何去做使用显然是 Rails 2.3 不需要的插件.这篇文章 表明可能毕竟 nginx 不支持 x-sendfile.

The available information seems contradictory and incomplete. This post shows how to do it with Apache, and hints that it can also be done with ngninx - but no examples. This post and this post show how to do it using the a plugin that apparently Rails 2.3 makes uncessary. This post suggests that maybe there isn't support for x-sendfile with nginx after all.

对于 Rails 现在可以自己做的事情,我宁愿不使用插件.

I'd rather not muck around with plugins for things Rails can now do by itself.

有没有人在不使用插件和 Rails 2.3/nginx/mongrel 的情况下获得类似 x-sendfile 的行为?如果没有,让它与插件(和/或monkeypatch)和Rails 2.3/nginx/mongrel一起工作的最佳文档是什么?

Has anybody gotten x-sendfile-like behavior to work using no plugins and Rails 2.3/nginx/mongrel? If not, what's the best documentation for getting it to work with a plugin (and/or monkeypatch) and Rails 2.3/nginx/mongrel?

推荐答案

主要思想:你的控制器所做的就是设置 nginx x-accel-redirect 标头.一旦您的控制器方法返回(这将非常快),nginx 将查看您的 Rails 应用程序集的标题.如果设置了 x-accel-redirect,则 nginx 提供静态文件.

The main idea: all your controller does is to set the nginx x-accel-redirect header. Once your controller method returns (which will be very fast), nginx will look at the header your Rails app set. If x-accel-redirect is set, then nginx serves the static file.

您的控制器看起来像:

def show  
  @attachment = Attachment.find(params[:id])  
  # Do anything else you need for authentication, etc. 

  head(:x_accel_redirect => '/files/' + @attachment.filename,  
   :content_type => @attachment.content_type,  
   :content_disposition => "attachment; filename="#{@attachment.filename}"")  
end  

仅凭这一点是行不通的.您还需要将位于 $RAILS_ROOT/files 的文件告诉 nginx.将此添加到服务器块内 nginx 配置的末尾:

This alone won't do the trick. You need to also tell nginx about the files located at $RAILS_ROOT/files. Add this to the end of your nginx config inside the server block:

location /files {
  root /path/to/rails_app;  
  internal;  
}

将静态文件放入 $RAILS_ROOT/files 中,它应该可以工作.无需插件或monkeypatching 已通过Rails 2.3.2 和2.3.14 测试.

Put the static file into $RAILS_ROOT/files and it should work. No need for plugins or monkeypatching Tested with Rails 2.3.2 and 2.3.14.

这篇关于使用 x-sendfile 通过 Rails 2.3 通过 Nginx 提供大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆