Stop Magento Permissions Errors ... Permanently

When working with customers not hosting with Sonassi Hosting, we continually run into the same permissions errors - along with the rest of the Magento using world. This isn't an issue if PHP runs as the same user as your FTP/SSH user, but if they are different, all kinds of headaches ensue.

Whenever granted root access to a server, we normally carry out the following, to rule out any future permissions headaches. Please bear in mind, this practice is secure for dedicated hosting but may present security issues with shared hosting if the Apache process isn't chroot'ed per user.

In our example, the user is sonassi and the group is apache

Add the FTP/SSH user to the Apache group

Most importantly, we need to make sure that the FTP/SSH user is part of the Apache group, in our example, its apache (but is also commonly www-data)

usermod -a -G apache sonassi

Keep adding as many users to the group as you have for FTP/SSH.

Reset original permissions

So before we start, lets make sure all the permissions are correct.

chown -R sonassi:apache /home/sonassi/public_html
find /home/sonassi/public_html -type d -exec chmod 775 {} ;
find /home/sonassi/public_html -type f -exec chmod 664 {} ;
find /home/sonassi/public_html/cron.sh -type f -exec chmod 775 {} ;

ACLs and Sticky Bits

ACLs in Linux allow us to define specific rules, in our case, what permissions files should inherit upon creation. A sticky bit (mentioned later) takes care of group inheritance, but does not help with the permissions, which is why we use ACLs.

Start by enabling ACL support on the active partition, please ensure your Kernel was compiled with ACL support

mount -o remount,acl /home

Now ACLs are enabled, we can set the ACL rules and group sticky bits:

setfacl -d -m u::rwx,g::rwx,o::rx /home/sonassi/public_html
chmod g+s /home/sonassi/public_html

But I don't have ACL support

If your Kernel doesn't support ACLs you can also use umask (which is a run time setting for BASH, FTP and PHP) to set the default file permissions. Magento usually sets umask(0) in index.php, however, it would be in your interests to change this.

In your index.php change the umask line to be

umask(022);

And in your BASH environment for SSH, set this in either you .bashrc or .bash_profile

umask 022

For your FTP server, you'll need to read the documentation for it, but the principal is the same.

All done

Now, whenever a new file is created, it will be created with the correct permissions and group, allowing your FTP/SSH user to create files and the web server will still be able to write and vice-versa.

Now sit back and relax knowing you'll never be recursively setting permissions again, or never experience the issue by changing your hosting to the UKs best Magento specialist host, Sonassi Hosting.