Setting Recursively Different File Permissions on Directories and Files in Linux
In the directory your Web Server is serving, you might need some permission on files and directories for security purposes. As www-data is the common user for Web Servers and it has to own a file for it to have access to it, sometimes we don’t create a file or directory with the www-data guy but might create with root or another user, with the permission set on the file or directory it won’t be possible for www-data to access. The permission I advice to use on web serving directories are 775 for directories and 644 or 664 for files, now how are you gonna set this recursively? Easy! with the find command, run this:
sudo find /path/to/dir -type d -exec chmod 775 {} + sudo find /path/to/dir -type f -exec chmod 664 {} +
Code Explained:
- find /path/to/dir : This searches in the specified directory
- -type d : Tells the command to search for directories only, while f is for files
- -exec chmod 664 {} + : This is a cool feature of the find command, it allows execution of other commands on a search result which we now tell it to change the file permission to 775 or 665
I hope this helps 🙂