After publishing your Laravel application to a real web server, you discover then some of your functionalities are failing.
You try to execute composer and artisan commands but the server politely responds that you and your little application don’t have appropriate permissions. Well, what a nice start to a day.
However, fear not, in this article you can see how to set the right permissions for your Laravel project.
Some people are suggesting to set 777 permission on the Laravel project folder. This is a big security risk and you absolutely should not do this. 777 permission allows anyone to read, write, and execute files in that directory, which potentially gives the opportunity to malicious people to upload any file and execute that file.
This is how you want to do it.
- Make web server the owner of the folder
sudo chown -R www-data:www-data /path-to-laravel-directory-on-server
sudo stands for superuser do and it allows you to run a command with elevated privileges and it will ask for the user password, the one you set when installing Linux
chown stands for change ownership and it allows you to change the user or group ownership of some file or directory
-R flag means that it will recursively descend within the specified directory
- Add our user to the webserver group
Since we gave webserver ownership of the files it will create a problem for us when we try to upload and work with files
sudo usermod -a -G www-data ubuntu
usermod command allows us to modify any attribute of an already created user
-a flag means to add someone already in a group to another group
-G flag means to add a specified group to a user
It is important to note that although -G flag is used to add group to a user, if alone without -a, it will remove all previous groups that the user belongs to. That is why it is important to use -a -G
- Change file permissions
sudo find / path-to-laravel-directory-on-server -type f -exec chmod 644 {} \;
644 permissions in short means that owner can change it, everyone one can read it
- Change directory permissions
sudo find / path-to-laravel-directory-on-server -type d -exec chmod 755 {} \;
755 permissions in short means that the owner can change and run it, everyone can run it.
- Give permissions to the webserver to read and write to cache and storage
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
chgrp stands for change group and it changes the group ownership of a file or directory.
chmod stands for change mode and it sets the permissions of files or directories.
You know, Laravel will hold the cache of views, routes, configs, and in storage, you have logs, and uploaded files, it needs permissions to work within those folders.
I hope that this will be useful for any of your future Laravel projects.