title: Serve protected media files with django
body: <p>I'd like Django to serve some media files (e.g. user-uploaded files) only for logged-in users. Since my site is quite low-traffic, I think I will keep things simple and do not use <code>django-sendfile</code> to tell Nginx when to serve a file. Instead I'll let Django/Gunicorn do the job. To me this seems a lot simpler and for a low traffic site this maybe more secure.</p>
  
  <p>But what is the best way to organize the file storage location? Media files are all stored below <code>MEDIA_ROOT</code> and this directory is served by Nginx in production. If I upload my files to <code>MEDIA_ROOT/protected/</code> I have to tell Nginx not to serve the files in the subdirectory <code>protected</code>.</p>
  
  <p>But is this a good idea? It seems a litte risky to me to allow Nginx access <code>/media/</code> in the first place and then protect the subdirectory <code>/media/protected/</code>. Wouldn't it be better not to use a subdirectory of <code>MEDIA_ROOT</code> to store protected files? </p>
  
  <p>But if I try something like this quick-and-dirty in my model:</p>
  
  <pre><code>upload_to='../protected/documents/%Y/%m/'
  </code></pre>
  
  <p>Django complains:</p>
  
  <pre><code>SuspiciousFileOperation at /admin/core/document/add/
  The joined path (/home/me/projects/project/protected/documents/2016/09/test.file) is located outside of the base path component (/home/me/projects/project/media)
  </code></pre>
  
  <p>So I thing it is not good practice to "leave" the <code>MEDIA_ROOT</code>.</p>
  
  <p>What is the best solution to store and serve protected media files?</p>