Skip to content

Instantly share code, notes, and snippets.

@matiaskorhonen
Created July 8, 2010 12:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save matiaskorhonen/467958 to your computer and use it in GitHub Desktop.
Save matiaskorhonen/467958 to your computer and use it in GitHub Desktop.
class DownloadsController < ApplicationController
DOWNLOAD_EXPIRY = 30.minutes
DOWNLOAD_SECRET = "MYSECRET"
def show
download = Download.find(params[:id])
# download.file_path - get the path to the file, relative to the downloads directory
serve_file(download.file_path)
render :nothing => true
end
private
def serve_file(path, mime_type = "application/octet-stream")
if Rails.env == "development" || Rails.env == "test"
send_file "#{Rails.root}/downloads/#{path}", :type => mime_type
else
time = (Time.now + DOWNLOAD_EXPIRY).to_i.to_s(16).upcase
hmac = Digest::MD5.hexdigest("/downloads/#{path}/#{DOWNLOAD_SECRET}/#{time}")
redirect_to "/downloads/#{path}/#{hmac}/#{time}"
end
end
end
./configure \
--prefix=/usr/local \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-pcre \
--add-module=../ngx_http_secure_download
# Upstream Unicorn app server
upstream unicorns {
server unix:/srv/APPLICATION/tmp/unicorn.sock;
}
# Front facing nginx
server {
listen 80;
server_name example.com;
root /srv/APPLICATION/public;
location ~ /downloads/(.*) {
rewrite ^/(.+)$ http://files.example.com/$1 last;
}
location / {
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://unicorns;
}
}
# Downloads server
server {
listen 80;
server_name files.example.com;
root /srv/APPLICATION;
location /downloads {
secure_download on;
secure_download_secret MYSECRET; # Change MYSECRET to something random
secure_download_path_mode file;
secure_download_fail_location /fail;
}
location /fail {
# Do whatever...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment