- How do I give www-data user to a folder in my home folder?
- 2 Answers 2
- Наследовании группы www-data в директории при создании файлов и папок в Ubuntu
- Создание пользователей
- Добавление пользователя в группу
- Задание прав на файлы и папки
- Права доступа
- www-data permissions?
- 3 Answers 3
- User setup
- Folder setup
- Setgid
- Grant a user permissions on www-data owned /var/www
- 6 Answers 6
How do I give www-data user to a folder in my home folder?
I have a folder: /home/myuser/folderA I want to give the www-data user write access to the above, while ‘myuser’ continues to have normal access (as it is myuser’s home folder anyway). Which commands do I need to use? Note: I don’t want www-data to have access to any other folders in /home/myuser/ . Thanks in advance.
2 Answers 2
First, add yourself into the group www-data
usermod -a -G www-data (your username)
chgrp www-data /home/myuser/folderA chmod g+rwxs /home/myuser/folderA
Should do the trick unless the permissions on your /home/myuser do not permit other users access.
The first command changes the group ownership of the folder to that of the webserver. The second command gives members of the www-data group read, write, enter-directory rights, and the group s flag will ensure that any files that get created inside that directory take www-data as the group — so if you create a file as myuser the www-data user will have access.
Nb. this also depends on the umask settings of both your user account and the webserver: you need to make sure that files created in folderA have group rw access (and directories created within need group rwx )
If your webserver does not have enter rights into your /home/myuser dir (quite sensible) then it’s not going to get in there unless you do something else. Two solns:
- sudo mount —bind /home/myuser/folderA /var/www/mysite/folderA (this is an ugly hack and would have to be repeated after reboot. But a powerful trick, also can be used to make folders accessible inside SSH jails.)
- Simply move the shared folder somewhere else, e.g. /home/shared-stuff/folderA .
The 2nd option is nicest. Let’s say the stuff in folderA is really public and you don’t care who sees it, you can set it up like
sudo mkdir -m777 /home/shared-stuff
Then you can put inside that, say, folderA with permissions as above, and folderB that www-data should not have access to with different permissions, e.g.
$ cd /home/shared-stuff ; ls -l drwxrwsr-x 2 myuser www-data 4096 Jan 17 21:46 folderA drwxrwx--- 2 myuser myuser 4096 Jan 17 21:46 folderB
Наследовании группы www-data в директории при создании файлов и папок в Ubuntu
Часто возникает необходимость, чтобы при создании файла или директории в Ubuntu автоматически задавалась группа и пользователь www-data . Для этого необходимо выполнить следующие шаги:
Создание пользователей
Создаём пользователя. Флаг -m нужен для создания домашней директории пользователя (для ее названия используется имя пользователя)..
useradd -m имя_пользователя
Для введения пароля нового пользователя или изменения пароля существующего введите в командной строке команду
Позже пользователь сможет изменить свой пароль при помощи команды passwd . Для этого ему понадобится ввести текущий пароль и новый.
Добавление пользователя в группу
Для добавления пользователя в группу используется команда usermod . Давайте добавим пользователя имя_пользователя в группу www-data . Опция -a означает append (добавить, прикрепить), а опция -G служит для указания названия вторичной группы.
usermod -a -G www-data имя_пользователя
Когда вы создаете пользователя при помощи команды adduser , для него автоматически создается первичная группа, носящая его имя. Поэтому в настоящее время пользователь имя_пользователя состоит в первичной группе имя_пользователя и вторичной www-data .
Также можно добавить пользователя сразу в несколько групп, перечислив их через запятую без пробелов (-G group1,group2,group3).
А эта команда изменит первичную группу пользователя имя_пользователя на группу www-data :
usermod -g www-data имя_пользователя
Задание прав на файлы и папки
Для того, чтобы все файлы в папке и подпапке также имели группу www-data , можно выполнить следующие команды:
sudo chgrp -R www-data польный_путь_к_папке sudo chmod -R g+s польный_путь_к_папке
Где польный_путь_к_папке — путь к папке, в которой находятся файлы. Первая команда задает группу www-data для всех файлов в папке и подпапках, а вторая команда устанавливает бит setgid для папки, что позволяет новым файлам, созданным в этой папке и подпапках, наследовать группу, установленную для этой папки.
Права доступа
Для предотвращения несанкционированного доступа к файлам и папкам веб-приложения необходимо установить соответствующие права доступа. Например, можно установить права 755 на директорию приложения и права 644 на файлы:
sudo chmod -R 755 польный_путь_к_папке sudo find польный_путь_к_папке -type f -exec chmod 644 > \; -print
Приветствую вас на сайте ZENCOD.ru! Здесь вы найдете статьи по web-разработке, javascript, linux и прочим темам, которые могут быть полезны.
www-data permissions?
So I have a directory in /var/www (called cake) and I need to allow www-data to write to it, but I also want to write to it (without having to use sudo). I’m afraid to change the permissions to 777 in case some other user on my machine (or a hacker) attempts to modify files in that directory. How do I only allow access for myself and Apache’s www-data?
3 Answers 3
sudo chown -R yourname:www-data cake
First command changes owner and group.
Second command adds s attribute which will keep new files and directories within cake having the same group permissions.
what can the user do with files created by www-data in cake itself, and files created by www-data in a directory which is created by www-data? for example, about edit, rename, delete operations? as i understand, renaming and deleting are not possible inside directory created by www-data, and editing of files creaed by www-data is not possible for user at all.
User setup
So let’s start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user ‘demo’ to the ‘www-data’ group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let’s set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I’ll add a quick note regarding 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 sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the ‘www-data’ group.
The first command will change the permissions for the public_html directory to include the «setgid» bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group ‘www-data’. If you have subdirectories, you’ll want to run that command for each subdirectory (this type of permission doesn’t work with ‘-R’). Fortunately new subdirectories will be created with the ‘setgid’ bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
Grant a user permissions on www-data owned /var/www
I have a simple web server setup for some websites, with a layout something like: site1: /var/www/site1/public_html/ site2: /var/www/site2/public_html/ I have previously used the root user to manage files, and then given them back to www-data when I was done (WordPress sites, needed for WP Uploads to work). This probably isn’t the best way. I’m trying to find a way to create another user (lets call it user1) that has permission to edit files in site1, but not site2, and doesn’t stop the files being ‘owned’ by www-data . Is there any way for me to do this?
6 Answers 6
If we check ownership of site1, we will find something like this,
ls -ld /var/www/site1/ drwxr-xr-x 2 root root 4096 Oct 24 21:06 site1/
This means that the directory is owned by user root, group root. While user root has write permission (plus read and execute permissions) to the directory, group root has only read and execute permissions.
We will want to change the group ownership to another (new) group and add user1 to that particular group. We will give write permission to that particular group as well.
Add user1 to the newly created group,
Check that user1 is really in that group,
The output should be a list something like,
Now we can change the group ownership of your intended directory.
sudo chown -vR :site1 /var/www/site1/ changed ownership of `/var/www/site1/' from root:root to :site1
Grant write permission to this new group owner,
sudo chmod -vR g+w /var/www/site1/ mode of `/var/www/site1/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)
Check that all the changes are indeed there,
ls -ld /var/www/site1/ drwxrwxr-x 2 root site1 4096 Oct 24 21:06 /var/www/site1/
So, the directory now is owned by user root, group site1. Both user root and group site1 have write permission (plus read and execute permissions) to the directory. Any user belonging to group site1 will enjoy all the privileges granted to that group.
Now login as user1, move to site1 directory and try to create a file in that directory,
echo "My User1 Site" > index.html bash: index.html: Permission denied
This failed since most likely the primary group of user1 is not site1. So, change to that group.
Try to recreate the file (beware that you have been moved to the home directory of user1 after changing group), this should work now. Since the created files will have world read permission, apache (or your web server) should not face any problem accessing them.
Also, as pointed out by dan08 in comment, you need to add www-data to site1 group.
sudo adduser www-data site1
On many (not all) distributions, www-data is the user under which the Apache web server runs. This also means that everything done by Apache (especially including PHP scripts) will be done with the permissions of user www-data (and also group www-data) by default. WordPress uses the user www-data to write files.
If you want to see how apache web server is running, issue the command,
ps aux | grep apache2 | less