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

November 25, 2016 2.4k views
Nginx Ubuntu Django

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?

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')
Have another answer? Share your knowledge.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!