Django File Upload with nginx / gunicorn - media p

2019-07-21 01:59发布

问题:

I'm trying to allow users of my django site to upload a file (mostly PDFs) to my server through a FileField on a model. However, I keep running into 'Errno 13 Permission Denied' when trying to use the upload field generated by my modelform.

I have found many potential solutions while searching around, but haven't been able to get anything to work properly so far. This is my first real deployment and I have probably confused myself. For reference, I am on Ubuntu 14.04, Django 1.6, & gunicorn+nginx.

Right now, my media root lies within my project directory at:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, "media/uploads")

The error indicates an issue with the proper directory, so it's going to the right spot.

I have tried to chown -r the media directory to www-data:www-data with no success. I poked around, figured out what user was running the python process and tried to set 'him' as the owner - didn't work. I flipped it back to its original owner and group (root:root) and tried to chmod -r to 755 and 770, both of which also failed to resolve the issue.

If I chmod -r to 777, then everything "works" - but that's not something I want to keep exposed for obvious reasons.

My static files are collecting and being served properly from a directory outside of my project root (/var/www/mysite/static), so I tried moving the media folder over there and repeating all of the above steps - same result.

How can I get my media folder to securely accept uploads and downloads from my users without leaving this security hole wide open?

Thank you!

回答1:

First of all, media files folder has to be in you project's path, otherwise you'll be getting SuspiciousOpertion exception from Django, so don't put it in /var/www.

Also, the fact that you are using nginx, is not that relevant, important part is which user is nginx/django project is running under, whichever user it is (normally www-data, at least with apache+mod_wsgi), that user should be the owner of the media folder.

Once you change the owner to the right user (I assume www-data): sudo chown -R www-data:www-data .../media, make sure permissions are correct: sudo chmod -R u+rwX .../media.

Hope it helped. Let me know if it didn't. :)



回答2:

Try upping the max_body_size in your nginx conf file:

server {
    ...

    client_max_body_size 250M;

    ...
}

By default it's set to 1M which is possibly too small depending on what you're uploading.