Django: Serving Media Behind Custom URL Django: Serving Media Behind Custom URL nginx nginx

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.


The basic idea is to get your Django view to redirect to a secure URL that is served by your media server.

See this list of suggestions by Graham Dumpleton, author of mod_wsgi.


Both httpd and Nginx have a way to specify a static file to serve via a header. The exact header varies though, so it's best to put something in the settings to pick the method.