File and folder permissions for webservers on linux os

Ideal file and folder permissions for webservers on linux operating system depends on webserver user, the ftp user, directories or files you need to perform the operations on. First you need to give proper ownership, then you can put permissions on files and directories are you are good to go.

Ownership of files and directories on linux has mainly 2 elements i.e user, group. Ownership is defined using chown command, while permission has 3 elements user, group and others i.e ugo. Permissions can be read, write or execute which are numerically and through sequence of characters as below:

4 – Read(r)

2 – Write(w)

1 – Execute(x)

 

Please go through below steps to stand good on ownerships and permissions:
Step 1) Know your webserver user:
Depends on your installation, you can try different options to know your webserver user, normally on amazon ami it is apache and on ubuntu it is www-data, for custom nginx installations it may vary.

ps aux | grep httpd
ps aux | grep apache
ps aux | grep apache2
ps aux | grep nginx

The output might be something like below, where you can see webserver user in first column:

Ownership

Step 2) Create a user group:

groupadd www-pub

Add apache (if webserver runs as httpd) user or www user (if webserver runs as apache2) and www-data (if webserver runs as nginx) to newly added group:

For apache user:

usermod -a -G www-pub apache
usermod -a -G www-pub ec2-user

For www-data user:

usermod -a -G www-pub www-data
usermod -a -G www-pub ubuntu

Assign ownership and group to document root, change it according to your case depends what your document root is:

Incase of ssh and ftp login with ec2-user:

chown -R ec2-user:www-pub /var/www/html

Incase of ssh and ftp login with ubuntu user:

chown -R ubuntu:www-pub /var/www/html

Note: -R gives recursive permission, that will change on subdirectories and the files inside.

Apply files and folder permissions:

find /var/www/html -type d -exec chmod 2775 {} \;
find /var/www/html -type f -exec chmod 0664 {} \;

Note: Inorder to make it more secure, you can give 2775 only to directories which needs to be writable and executable by webserver user (apache or ubuntu) and keep other directories to be writable and executable by only owner. In the similar way you can make 0644 for all files and 0664 for files writable by Webserver.


find /var/www/html -type d -exec chmod 2755 {} \;
find /var/www/html/uploads -type d -exec chmod 2775 {} \;
find /var/www/html -type f -exec chmod 0644 {} \;
find /var/www/html/wp-config.php -type f -exec chmod 0664 {} \;
Please follow and like us:
20

Add a Comment

Your email address will not be published. Required fields are marked *