Django: What setting to be done in NGINX Conf to serve media file to logged in users only.

Posted November 25, 2016 4.1k views

Hi I have a project hosted on Digitalocean. What changes should i make to my project or NGINX so that media files are not served to users who are not logged in?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

This guide will walk you through setting up basic authentication in Nginx. Additional steps might be needed if you authenticate your users in some other way or have an existing authentication system already in place.

by finid
In this tutorial, you'll learn how to restrict access to an Nginx-powered website using the HTTP basic authentication method on Ubuntu 14.04. HTTP basic authentication is a simple username and (hashed) password authentication method.
  • This is totally unrelated with question asked. Need a django specific solution.

    • I apologize, I missed that the question was tagged Django. It seems the best option for implementing this in Django is the XSendfile method which is supported by apache. This thread compares some methods and includes examples like this one;

      def serve_file(request, filename):
          fullname = myapp.settings.PRIVATE_AREA+filename
              f = file(fullname, "rb")
          except Exception, e:
              return page_not_found(request, template_name='404.html')
              wrapper = FileWrapper(f)
              response = HttpResponse(wrapper, mimetype=mimetypes.guess_type(filename)[0])
              response['Content-Length'] = os.path.getsize(fullname)
              response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
              return response
          except Exception, e:
              return page_not_found(request, template_name='500.html')