If you've stumbled upon this post, it most likely means that you're trying to fix a nasty issue affecting your Linux server: every time you upload some new files to a folder (such as var/www) that has specific group access (such as www-data) using your favorite SSH or FTP(s) client, those files are created with <user>:<user> ownership rights - instead of <user>:www-data permissions like you would like to.
Such behavior basically prevents Apache, NGINX, and any other service that is configured to use www-data permissions from accessing those files, as well as other users different than you, until you use chown/chgrp commands to fix it.
Is there a way to specify a default group when creating new files, instead of using your username's group? As a matter of fact, the answer is YES. In this post, we'll see how we can do that.
How to Set a Default Group for new Files
Here's what we need to do to set a default group when adding new files in a folder:
1 2 |
chgrp www-data /var/www chmod g+s /var/www |
Once we do that, all existing and new files created in the /var/www directory will be owned by the www-data group. More precisely, the first command will change the current permissions for the existing files, while the latter will set the default behavior for new files. Needless to say, if the folder(s) are already owned by the www-data group, we can omit the first command and just set the default behavior for all new files.
However, it's worth noting that the above commands will only change the behavior of the root /var/www folder - not the sub-folders within it. If we want to apply the same behavior for the whole directory tree - the /var/www folder and all subfolders - we need to execute a recursive approach using the find command in the following way:
1 2 |
find /var/www -type d -exec chgrp www-data {} + find /var/www -type d -exec chmod g+s {} + |
That's it.
Using a script
If you have a lot of folders (or servers) which you want to apply this fix to, you might want to perform this task with the help of a bash script.
Here's the set_default_group.sh script we are using in our web servers:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/bin/bash # # This script configures a given folder (and all subfolders) permissions so that each file/folder created there will have the www-admins group by default. # ref: https://www.ryadel.com/en/linux-set-default-group-creating-new-files-ftp-ssh-ubuntu/ # # execute it with the following command: # bash set_default_group.sh /var/www www-data # FOLDER=$1 # <-- root folder GROUP=$2 # <-- group find ${ROOT} -type d -exec chgrp ${GROUP} {} +; find ${ROOT} -type d -exec chmod g+s {} +; |
Feel free to use it!
Conclusions
We hope that this small piece of advice will help other system administrators getting rid of this nasty "ownership issue" as well.