I am developing a django API which will be running on top of Apache2 via WSGI on a server running Ubuntu.
Users will be able to upload pictures they take to the server using a POST request. The API processes this request and then attempts to write the image to
chmod 777 -R media
import os, sys
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
MEDIA_ROOT = '/var/www/media/'
MEDIA_URL = os.path.join(BASE_DIR,'/media/')
Alias /media/ /var/www/media/
I have solved this myself in the end.
When running on the development machines, I am in fact running using my current user's privileges. However, when running on the deployment server, I am in fact running through
wsgi, which means it's running using
www-data is neither the owner nor in the group of users that own
/var/www. This means that
www-data is treated as
other and has the permissions set to others.
The BAD solution to this would be to do:
sudo chmod -R 777 /var/www/
This would give everyone full access to everything in
/var/www/, which is obviously a very bad idea.
Another BAD solution would be to do:
sudo chown -R www-data /var/www/
This would change the owner to
www-data, which opens security vulnerabilities.
The GOOD solution would be:
sudo groupadd varwwwusers sudo adduser www-data varwwwusers sudo chgrp -R varwwwusers /var/www/ sudo chmod -R 770 /var/www/
www-data to the
varwwwusers group, which is then set as the group for
/var/www/ and all of its subfolders.
chmod will give read, write, execute permissions to the owner and the group, while blocking any other users from accessing it.