Securely setting Files and Folder permissions on Laravel 5
Securely setting Files and Folder permissions on Laravel 5
Introduction:
Handling file and folder permission in Laravel 5 and above.
I had a similar issue while running Laravel Application and Cron Jobs on the same server.
So what is the problem here?
The issue here was while creating a log file.
When the log files are created by the Web Application the file permission would look like.
| -rw-r--r-- 1 www-data www-data 1646 May 11 2017 laravel.log //Permissions are set to Apache User |
Similarly, when the log files are created by the Cron Jobs then the file would have its owner and group owner as your Apache User.
| -rw-r--r-- 1 ubuntu ubuntu 1646 May 11 2017 laravel.log //Permissions are set to User |
So, if the log file was created by Web Application same file can't be used bt Apache User and vice versa
Error would look something like this
The stream or file "/var/www/html/project-folder/storage/logs/laravel-2017-12-18.log" could not be opened: failed to open stream: Permission denied
The only way to overcome this problem take quick action by setting files and folder permission to their folder to 777 and project started running.
Security Concerns:
However, if you notice this is really a bad practice if you do this meaning if you set 777 permission to your project directory that says your server is open to the world.Meaning anyone can visit your application can have read, write and execute permission on your server.
In Simple words – anyone can read the data from your application, write the data and execute the files, so hackers can easily upload file or virus or malware and execute to damage your project.
Step One:
Find the web server user.
| ps aux | egrep '(apache|httpd)' |
You should get output similar to this:
This output clearly saying that Apache is running www-data, so we get our user.
Step Two:
change the directory/project-directory owner to www-data, use following command:| sudo chown -R www-data:www-data /var/www/path/your/project/ |
Step Three:
Set Folders permissions to 755 and file permissions of your project to 644:Folder/Directory Permissions:
| sudo find /var/www/example-project-name/ -type d -exec chmod 755 {} \; |
Files Permissions:
| sudo find /var/www/example-project-name/ -type f -exec chmod 644 {} \; |
Step Four:
But Laravel still needs read and write access to the storage and bootstrap/cache folder, we can fix this by giving read and write access to web server i.e www-data:| sudo chgrp -R www-data /var/www/project-name/storage /var/www/project-name/bootstrap/cache sudo chmod -R ug+rwx /var/www/project-name/storage /var/www/project-name/bootstrap/cache |
Step Five:
Finally, add a user to the group:| sudo usermod -a -G www-data ubuntu |
Now, the issue is resolved also secured.


Thank you for sharing this informative post. Looking forward to reading more.
ReplyDeleteLaravel Development Company