Nginx Secure Links With Rails
When building Elemental Beats I wanted to make sure that the download links I gave my customers for their purchase where protected and had an expiration date.
There are a number of ways to implement secure download links in rails, but I think the best option is to use the ngx_http_secure_link_module for nginx. Its actually quite straight forward to implement and provides you with secure time expiring download links, and the best part is that since nginx is serving the files you don't tie up a rails process to serve the file so your site can stay extra fast.
Here is how to implement it with Rails.
First you'll need to compile nginx with the secure link module. So this means you can't just use the standard nginx package from
apt-get without any customization. Don't worry though its easy to compile nginx just download the source and pass this option to your configure script.
Once you have nginx compiled and installed with the http secure link module, you'll need to set it up.
First add a server block like this to your nginx.conf. Just make sure to change the server_name and root directives to match your site. Also change the DOWNLOAD_SECRET string to something unique and secret.
Now restart nginx, and thats all you will have to do with nginx. Now make sure to place all your files in the downloads directory of your files.domain path.
Now on to Rails.
In your Rails code you basically need to generate the required params that nginx expects for each file you serve from your files subdomain. To do this I have a method in my Order model that looks like this:
Just note that my Order model in the code above has a
file_path method that when called returns the path to the file inside the downloads directory folder. Also note the DOWNLOAD_SECRET env variable, that should match the string you put in your nginx config file.
And thats all it takes to have nginx serve secure download links from your rails app.