Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save geordee/9374884 to your computer and use it in GitHub Desktop.
Save geordee/9374884 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment