Django: Serving Media Behind Custom URL

To expand on the previous answers you should be able to modify the following code and have nginx directly serve your download files whilst still having the files protected.

First of all add a location such as :

location /files/ {
   alias /true/path/to/mp3/files/;
   internal;
}

to your nginx.conf file (the internal makes this not directly accessible). Then you need a Django View something like this:

def song_download(request, song_id):
    try:
        song = Song.objects.get(id=song_id)
        response = HttpResponse()
        response['Content-Type'] = 'application/mp3'
        response['X-Accel-Redirect'] = '/files/' + song.filename
        response['Content-Disposition'] = 'attachment;filename=" + song.filename
    except Exception:
        raise Http404
    return response

which will hand off the file download to nginx.

Leave a Comment