Join us on Facebook!
— Written by Triangles on November 09, 2019 • updated on November 10, 2019 • ID 76 —
This is something that has been bugging me since my day one of web development. In this article I want to sort it out for good.
The website is stored in a Linux server like Ubuntu, and it is run by a web server like Apache or Nginx. You are the project owner and the sole user responsible for maintaining it.
The site is made of static content like CSS, images, HTML pages as well as some dynamic content generated by the web server on the fly — for example, a PHP script that manages file upload. So the web server needs to read the static content in order to display it to the public, as well as write data into the site folder as instructed by the script files.
Finally, let's pretend your user is called
john, the website folder is located in
/var/www/my-website.com/ and the web server belongs to the
www-data user group.
Your user will be the owner of the website directory and will have full read, write and execute permissions. The web server will be the group owner and initially will have read and execute permissions, except for some folders where it will have write access. No one else will be allowed to mess around with the whole website directory.
To get started, login into your server and run the four commands below.
chown -R john /var/www/my-website.com/
This command sets
john as the owner of every file and folder inside the directory (
-R stands for recursive).
chgrp -R www-data /var/www/my-website.com/
This command sets
www-data as the group owner of every file and folder inside the directory. Recursive mode, as above.
chmod -R 750 /var/www/my-website.com/
The third command sets the permissions: read, write and execute (7) for the owner (i.e. you), read and execute (5) for the group owner (i.e. the web server), zero permissions at all (0) for others. Once again this is done on every file and folder in the directory, recursively.
chmod g+s /var/www/my-website.com/
The last command makes all files/folders created within the directory to automatically take on the group ownership of the parent folder, that is your web server. The
s flags is a special mode that represents the setuid/setgid. In simple words, new files and directories created by the web server will have the same group ownership of
my-website.com/ folder, which we set to
www-data with the second command.
If you have folders that need to be writable by the web server, you can just modify the permission values for the group owner so that
www-data has write access. Run this command on each writable folder:
chmod g+w /var/www/my-website.com/<writable-folder>
For security reasons apply this only where necessary and not on the whole website directory.
Server Fault - What permissions should my website files/folders have on a Linux web server?
Unix & Linux - 'chmod g+s' command
Wikipedia - chmod