Skip to content

Instantly share code, notes, and snippets.

@ebeigarts
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebeigarts/9410688 to your computer and use it in GitHub Desktop.
Save ebeigarts/9410688 to your computer and use it in GitHub Desktop.
Carrierwave + nginx X-Accel-Redirect

Carrierwave + nginx X-Accel-Redirect

nginx.conf

location /protected {
  internal;
  alias /var/www/myapp/current/protected;
}

location / {
  proxy_set_header X-Sendfile-Type X-Accel-Redirect;
  proxy_set_header X-Accel-Mapping (/var/www/myapp/current|/var/www/myapp/releases/[\d]+)/protected/=/protected/;
  # ...
}

.gitignore

# Ignore Carrierwave upload files.
/protected

config/environments/production.rb

# Specifies the header that your server uses for sending files.
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

config/initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.storage = :file
  config.store_dir = 'protected/uploads'
  config.cache_dir = 'protected/uploads/tmp'
end
CarrierWave.root = Rails.root.to_s

config/deploy.rb

after "deploy:finalize_update", "deploy:symlink_shared_protected"

namespace :deploy do
  task :symlink_shared_protected, :roles => :app do
    run "mkdir -p #{shared_path}/protected"
    run "rm -rf #{latest_release}/protected"
    run "ln -nfs #{shared_path}/protected #{latest_release}/protected"
  end
end

app/uploaders/uploader.rb

class Uploader < CarrierWave::Uploader::Base
  # Override the directory where uploaded files will be stored.
  def store_dir
    "protected/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

app/controllers/*

send_file @attachment.file.path
@infernalsirius
Copy link

I used the current_path method from carrierwave. The controler code send_file @attachment.file.path wasn't getting the right path formatted the way it wanted.

send_file @attachment.file.current_path

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