Managing File Permissions with chmod and chown
Understanding Linux Permissions
Every file has three permission sets: owner, group, and other. Each set has three bits: read (r=4), write (w=2), execute (x=1).
ls -la /var/www/html
# -rwxr-xr-x 1 root root 1234 Jan 1 00:00 index.php
# ^^^ = owner permissions
# ^^^ = group permissions
# ^^^ = other permissions
chmod — Change Permissions
Numeric (octal) mode:
chmod 755 /var/www/html # rwxr-xr-x (directories)
chmod 644 /var/www/html/index.php # rw-r--r-- (files)
chmod 600 ~/.ssh/id_ed25519 # rw------- (private keys)
chmod -R 755 /var/www/html # Recursive
Symbolic mode:
chmod u+x script.sh # Add execute for owner
chmod g-w file.txt # Remove write from group
chmod o-r file.txt # Remove read from others
chmod a+r file.txt # Add read for all
chown — Change Owner
chown root:root /etc/nginx/nginx.conf # owner:group
chown www-data:www-data /var/www/html -R # Recursive
chown -R user:user /home/user/ # Change entire home dir
Recommended Permissions for Web Hosting
# Set directories to 755, files to 644
find /var/www/mysite -type d -exec chmod 755 {} \;
find /var/www/mysite -type f -exec chmod 644 {} \;
# Set ownership to web server user
chown -R www-data:www-data /var/www/mysite
Special Permissions
chmod 4755— setuid (runs as owner's identity)chmod 1755— sticky bit (only owner can delete files in directory, used on /tmp)