Restricting access to static files in Django/Nginx Restricting access to static files in Django/Nginx nginx nginx

Restricting access to static files in Django/Nginx


If you are serving small files, you can indeed use Django to serve them directly, writing the file into the HttpResponse object.

If you're serving large files however, you might want to leave that task to your webserver, you can use the X-Accel-Redirect header on Nginx (and X-Sendfile for Apache & Lighttpd) to have your webserver serve the file for you.

You can find more information about the header itself in Nginx's documentation here, and you could find some inspiration as to how to use that in Django here.

Once you're done sending files through Django views, enforcing user authentication should be pretty straightfoward using Django's auth framework.


How about enforcing user==owner at the view level, preventing access to the files, storing them as FileFields, and only retrieving the file if that condition is met.

e.g. You could use the @login_required decorator on the view to allow access only if logged in. This could be refined using request.user to check against the owner of the file. The User Auth section of the Django documentation is likely to be helpful here.

The other option, as you mention is via S3 itself, generating urls within Django which have a querystring allowing an authenticated user access to download a particular s3 object with a time limit. Details on that can be found at the s3 documentation. A similar question has been asked before here on SO.


I've used django-private-files with great success, it enforces protection at the view level and uses differente backends to do the actual file transfer.