Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Set User and Group Ownership for Future Files and Folders

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?

like image 583
Rick Helston Avatar asked Aug 07 '15 20:08

Rick Helston


2 Answers

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
  • The -d flag specifies the operations apply to the Default ACL.
  • The -R flag sets operations to apply recursively
  • The -m indicates it will be a modification operation

Then after that it's pretty straight forward

  • u:USERNAME:permissions
  • g:GROUPNAME:permissions

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.

like image 55
Gene Avatar answered Sep 20 '22 23:09

Gene


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
like image 35
isapir Avatar answered Sep 19 '22 23:09

isapir