Django: Serving Media Behind Custom URL

后端 未结 3 709
既然无缘
既然无缘 2020-12-04 09:03

So I of course know that serving static files through Django will send you straight to hell but I am confused on how to use a custom url to mask the true location of the fil

3条回答
  •  渐次进展
    2020-12-04 09:15

    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.

提交回复
热议问题