chown: change file owner and group
chown changes which user and group own a file. Together with chmod it decides who can do what. Only root can give files away to another user.
chown [-R] user[:group] file ...
chgrp [-R] group file ...
Examples
sudo chown anna report.txt # new owner
sudo chown anna:staff report.txt # owner and group
sudo chown :www-data upload.php # only the group (same as chgrp www-data)
sudo chown -R deploy:www-data /var/www/site # a whole tree
sudo chown --reference=index.html new.html # copy owner and group from another file (GNU)
sudo chown 1001:1001 /srv/data # numeric IDs, e.g. for containers
sudo chown -h anna link # change a symbolic link itself, not its target
chgrp developers project/ # group change, allowed for the owner if they are a member
A typical web site layout
Let a deploy user own the code and let the web server only read it, except for the upload directory:
sudo chown -R deploy:www-data /var/www/site
sudo find /var/www/site -type d -exec chmod 750 {} +
sudo find /var/www/site -type f -exec chmod 640 {} +
sudo chown -R www-data:www-data /var/www/site/uploads
Giving the web server user ownership of all the code (chown -R www-data everything) means a hacked application can rewrite itself. On RHEL the web user is apache, on nginx-based setups sometimes nginx.
Things to know
chown -Rfollows no symbolic links by default, which is safe. With-Lit would follow them into other directories.- Changing the owner usually clears SUID and SGID bits, for security.
- Files show a number instead of a name in
ls -lwhen their user ID has no account, for example after copying from another system or deleting a user. Find them withfind / -xdev -nouser. - On NFS with
root_squash, even root on the client cannot change ownership of files on the server.