When creating a website, what permissions and directory structure?

5,078

Permissions can be granted on owner, group and others.

First, decide what permissions are necessary and which users are involved:

  • Nginx running as www-data (group www-data): read-only
  • php-fpm running as www-data (group www-data): read and write
    (if you'd like to allow operations like chmod, you should run php-fpm as the SFTP user. Beware: if someone can execute command on your server from PHP, he/she will be able to modify your files too, like .bashrc!)
  • sftp / SSH: full permissions
  • Other users: no read and write permissions

Only the owner of a file / directory can change permissions and it's preferred to give the SSH user this ownership. Why? Because it's idiot that you cannot modify your own files in the webroot and doing everything as root is a bad idea.

Regular users cannot do change the group of a file / directory, only root can do that. A special SETGID bit makes every file and directory in a directory inherit the group. With the right permissions set, both php-fpm and the SSH user can modify files.

  • Owner: your SSH user
  • Group: www-data
  • Permissions for files: rw-rw---- (0660)
  • Permissions for directories: rwxrwx--- (2770) The execute bit (2) is needed to descend into a directory. Execute info coreutils 'file permissions' to get more information about this bit
  • umask 007 so that the owner and group can write to files / directories and other users do not get permissions.

Assuming that your webroot is located at /var/www/website1, change the owner/group and permissions by running:

sudo chown -R your_ssh_user_here:www-data /var/www/website1
sudo find /var/www/website1 -type f -exec chmod 660 {} \;
sudo find /var/www/website1 -type d -exec chmod 2770 {} \;

Add yourself to the www-data group:

sudo usermod -a -G www-data your_ssh_user_here

You need to re-login to become a member of the group.

Additional configuration is needed to ensure that websites cannot access other files if php-fpm is running as the same user.

Share:
5,078

Related videos on Youtube

Dan Simmons
Author by

Dan Simmons

Student at Georgia Tech in Atlanta, GA.

Updated on September 18, 2022

Comments

  • Dan Simmons
    Dan Simmons over 1 year

    I'm posing this question because I still haven't found a uniform method that I'm particularly fond of. Ideally, this combination of directory structure and permissions should suit any web server (don't assume Apache). I should also mention that I'm concerned only with *nix servers.

    I'm primary looking for:

    • Best combination of uid/gid/other (names and octets)
    • Relatively secure (doesn't have to be uber paranoid)
    • Easy to use / maintain (CMS's are able to self-update, no permission issues)

    Just for reference, the current stack I'm working on is Ubuntu 11.04 + Nginx + php-fpm + Wordpress, although the ideal solution should work for any website