How do I force group and permissions for created files inside a specific directory?
To set the group, give /var/www
the setgid bit:
chgrp www-data /var/www
chmod g+s /var/www
To also adjust subdirectories: find /var/www -type d -exec chmod g+s {} +
This will make all newly created files inherit the parent directory's group, instead of the user's.
To set the default group permissions, you will have to use ACLs. Set a "default" ACL:
setfacl -m "default:group::rwx" /var/www
To also adjust subdirectories: find /var/www -type d -exec setfacl -m d:g::rwx {} +
Note: The file system must have ACL support enabled. Sometimes it is on by default; on ext3 or ext4 you might get "Operation not supported", in which case it must be enabled manually:
For a currently mounted filesystem:
mount -o remount,acl /
Permanently – one of the methods below:
at fstab level: edit
/etc/fstab
to haveacl
in the options fieldat filesystem level:
tune2fs -o acl /dev/diskname
This might have gotten a few people stuck with 'grawity' answer on setgid, if the folder's group is different from your own you may need to run chmod as root but you won't get any error indicating you need to do this.
$ ls -ld dir
drwxrwxr-x 2 luke testgroup 4096 Mar 9 10:44 dir
$ chmod g+s dir #no errors
$ ls -ld dir
drwxrwxr-x 2 luke testgroup 4096 Mar 9 10:44 dir #but nothing changed
$ touch dir/nosudo && ls -l dir/
-rw-rw-r-- 1 luke luke 0 Mar 9 10:51 nosudo #and the group is still wrong
$ sudo chmod g+s dir
$ ls -ld dir
drwxrwsr-x 2 luke testgroup 4096 Mar 9 10:44 dir #the setgid bit is now on
$ touch dir/withsudo && ls -l dir/
-rw-rw-r-- 1 luke luke 0 Mar 9 10:51 nosudo
-rw-rw-r-- 1 luke testgroup 0 Mar 9 10:51 withsudo #and group is set