通过Rails 2.3使用x-sendfile通过Nginx服务大文件 [英] Serving Large Files Through Nginx via Rails 2.3 Using x-sendfile
问题描述
比方说,我有一个由nginx开头并由mongrel提供服务的Rails 2.3.2应用程序,在该应用程序中,我需要通过Rails提供一个较大的静态文件(以控制对其的访问).我希望Rails应用将文件传输委派给nginx,以避免阻塞杂种实例.
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完成-但没有示例. 这篇文章和这篇文章建议也许毕竟不支持使用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?
推荐答案
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
仅此一项并不能解决问题.您还需要告诉nginx有关$ RAILS_ROOT/files中的文件.将此添加到服务器块内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.
这篇关于通过Rails 2.3使用x-sendfile通过Nginx服务大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!