I was changing user and group ownership using the following command:
sudo chown -R apache:www /var/www
However, I noticed that whenever I added a new file or folder to that directory, the owner would be my current username instead of the intended user, apache. How can I modify the above command so that all future folders and files will be owned by apache:www? Or do I need to use an extra command?
You can use ACLs to do this. For example:
$ ls -ld /var/www
drwxr-xr-x 2 apache www 4096 Aug 7 13:53 /var/www
$ sudo setfacl -dRm u:apache:rwX,g:www:rwX /var/www
$ ls -ld /var/www
drwxr-xr-x+ 2 apache www 4096 Aug 7 13:53 /var/www
$ getfacl /var/www
# file: var/www
# owner: apache
# group: www
user::rwx
group::r-x
other::r-x
default:user::rwx
default:user:apache:rwx
default:group::r-x
default:group:www:rwx
default:mask::rwx
default:other::r-x
When new files are created there by they will still be owned by your user, but there will also be an ACL set on it granting privileges to the apache user:
$ touch donkey
$ ls -l donkey
-rw-rw-r--+ 1 gene gene 0 Aug 7 13:57 donkey
$ getfacl donkey
# file: donkey
# owner: gene
# group: gene
user::rw-
user:apache:rwx #effective:rw-
group::rwx #effective:rw-
group:www:rwx #effective:rw-
mask::rw-
other::r--
An overview of the command:
setfacl -dRm u:apache:rwX,g:www:rwX /var/www
-d
flag specifies the operations apply to the Default ACL.-R
flag sets operations to apply recursively-m
indicates it will be a modification operationThen after that it's pretty straight forward
These entries must be separated by a comma.
The X
permission (note: it's uppercase) means it will only be applied to directories and not files.
You can achieve that on the group level by using the SETGID
(SET Group ID) flag of chmod
:
chmod g+s <directory>
From the docs:
On most systems, if a directory’s set-group-ID bit is set, newly created subfiles inherit the same group as the directory, and newly created subdirectories inherit the set-group-ID bit of the parent directory.
Once you set that, newly created files and directories inside <directory>
will be set to <group>
. e.g.
chmod g+s /srv/www
will cause newly created files and directories inside /srv/www
to have the group www
.
You can verify that by executing ls -al
which will show s
for the group "execute" permission on the directory. e.g.
drwxr-sr-x. 5 apache www 4096 Mar 13 20:32 www
^
SETGID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With