Linux – Granting write permissions to www-data group


I am creating a website and part of the function is to write out user generated data with php. I'm using nginx on Ubuntu 13.04. A the moment I'm only testing and everything is served through nginx on locahost.

My php script fails to write the text file (although I can do this manually) and I think it's a permissions problem for writing to my /var/www/ directory.

At the moment I (iain) own this directory but it seems it would make more sense to transfer ownership of the /var/www directory and everything inside that to the www-data user (or should that be group?) and add myself to the www-data group. Is the following the right way to do this?

useradd -G www-data iain
chown -R www-data:www-data /var/www/
chmod 775 /var/www

So does this mean anyone in the www-data group can now read, write and exec in /var/www?

Best Answer

First, useradd creates a new user. As you (iain) already exist, you want to call usermod instead. So that would be:

sudo usermod -aG www-data iain
addgroup www-data

(note the -a on Debian-based servers (Ubuntu included) that will add you to that group, and keep your membership to other groups. Forget it and you will belong to the www-data group only - could be a bad experience if one of them was wheel. On SUSE-type servers the option is -A instead of -aG so read man usermod carefully to get it right.)

Second, you don't want apache to have full rw access to /var/www: this is potentially a major security breach. As a general rule, allow only what you need, and nothing more (principle of least privilege). In this case, you need apache (www-data) and you (www-data group) to write (and read) in /var/www/, so

sudo chown -R www-data:www-data /var/www/
sudo chmod -R 770 /var/www/

Edit: to answer your original question, yes, any member of www-data can now read and execute /var/www (because the last bit of your permissions is 5 = read + exec). But because you haven't used the -R switch, that applies only to /var/www, and not to the files and sub-directories it contains. Now, whether they can write is another matter, and depends on the group of /var/www, which you haven't set. I guess it is typically root:root, so no, they (probably) can't write.

Edit on 2014-06-22: added a note that -aG option is valid on Debian-based servers. It apparently varies with the distribution, so read man carefully before executing.

Related Question