Serving Large Files Through Nginx via Rails 2.3 Using x-sendfile

后端 未结 1 365
刺人心
刺人心 2020-12-08 23:36

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 wa

相关标签:
1条回答
  • 2020-12-08 23:56

    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.

    Your controller will look something like:

    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  
    

    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;  
    }
    

    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.

    0 讨论(0)
提交回复
热议问题