User setting
So, let's start by adding the primary user to the Apache user group:
sudo usermod -a -G www-data demo
This adds a custom demo to the www-data group. Make sure you use both the -a and -G options with the usermod command shown above.
You will need to log out and log back in to enable the group change.
Now check the groups:
groups ...
So, now I am a member of two groups: My own (demo) and the Apache group (WWW data).
Folder setting
Now we need to make sure that the public_html folder belongs to the main user (demo) and is part of the Apache group (www-data).
Let it be installed:
sudo chgrp -R www-data /home/demo/public_html
As we talk about permissions, I will add a brief note on the sudo command: itβs a good habit to use absolute paths (/ home / demo / public_html) as shown above, rather than relative paths (~ / Public_html). It ensures that sudo is used in the correct location, etc.
If you have a public_html folder with symbolic links, then be careful with this command, since it will follow symbolic links. In those cases of the working folder public_html, manually change each folder.
Setgid
Good so far, but remember that the command we just gave affects only existing folders. What about the new?
We can establish ownership so that everything new is also in the "www-data" group.
The first command will change the permissions for public_html to enable the setgid bit:
sudo chmod 2750 /home/demo/public_html
This ensures that the www-data group is assigned to the new files. If you have subdirectories, you will want to run this command for each (this type of permission does not work with '-R'). Fortunately, new subdirectories will be created using the setgid bit set automatically.
If we need to allow write access to Apache, in the uploads directory for example, then set permissions for this directory as follows:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
Permissions need to be set only once, since new files will automatically be assigned the correct ownership.