Skip to content

Instantly share code, notes, and snippets.

@ozgun
Last active August 23, 2016 03:03
Show Gist options
  • Save ozgun/4547357 to your computer and use it in GitHub Desktop.
Save ozgun/4547357 to your computer and use it in GitHub Desktop.
Rails 3.2.x: Serving files with nginx using X-Accel-Redirect header (capistrano deploy)
# Assumptions:
* Rails 3.2.x
* nginx
* capistrano deploy
* "X-Accel-Mapping header missing" messages in nginx error.log file
* You want to serve static files with nginx instead of Rails
# nginx configuration:
passenger_set_cgi_param HTTP_X_ACCEL_MAPPING "/home/user/rails_app/shared/files/=/documents/";
passenger_pass_header X-Accel-Redirect;
location ~ ^/documents/(\d\d\d)/(\d\d\d)/(\d\d\d)/(.*)$ {
alias /home/user/rails_app/shared/files/$1/$2/$3/$4;
internal;
}
# DocumentsController:
def index
@document = Document.find(params[:id])
# @document.path #=> /home/user/releases/20130111141529/files/000/000/001/file.txt
send_file @document.path.sub(/releases\/\d{14}/, 'shared')
end
# Rails: config/environments/production.rb
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# Request:
http://localhost:3000/documents/1
# References:
* http://stackoverflow.com/questions/954470/serving-large-files-through-nginx-via-rails-2-3-using-x-sendfile
* http://airbladesoftware.com/notes/rails-nginx-x-accel-mapping
* http://wiki.nginx.org/HttpCoreModule#alias
* http://greenlegos.wordpress.com/2011/09/12/sending-files-with-nginx-x-accel-redirect/
* http://stackoverflow.com/questions/6237016/message-x-accel-mapping-header-missing-in-nginx-error-log
@simaob
Copy link

simaob commented Jan 13, 2014

Hi, this was really useful to solve our similar issue! We just did something different which was to use the Pathname library instead of the method sub to obtain the real path to the file, by doing:

Pathname.new(@document.path).realpath

It looked more robust! =)

Thanks though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment