Friday, April 22, 2022

[SOLVED] Laravel Permission Denied Error on CentOs 7

Issue

I have just installed CentOs 7 with httpd, PHP 7.3 and MariaDB. I configured the virtualhost with the below:

<VirtualHost *:80>
  ServerName tenancy
  DocumentRoot /var/www/vhosts/tenancy/public
</VirtualHost>

I got the application displaying the default laravel welcome page but every page that interact with database got SQLSTATE[HY000] [2002] Permission denied (SQL: select * from tenant_modules where (tenant_id = 28))

While for every api call, I got file_put_contents(/var/www/vhosts/tenancy/storage/framework/cache/data/44/d1/44d142505dd1a3b497197e2f459d2aec779e9ed6): failed to open stream: Permission denied

I have set the permission on the www folder to 777 -R and even done chcon -R -t httpd_sys_rw_content_t -R \var\www and still nothing changed. Also, I have written a php function just to test mysql ext and that works.

But when I run php artisan serve, it works fine. Do you have an idea of what could be the solution?


Solution

It looks like a permission issue. I suspect your Apache user doesn't have permissions to read and write in your Laravel application folder.

I'm not sure what the Apache user/group is on CentOs. I will assume it's www-data, please change as required.

Disclaimer: This works on my machine (Debian) but there may be some better ways to set your Laravel app permissions. Feedbacks are welcome.


  1. Add your user to www-data group:

    sudo usermod -aG www-data youruser

  2. Change your project user and group ownership:

    sudo chown -R youruser:www-data /var/www/your-project/

  3. Change your project files permissions to 664:

    sudo find /var/www/your-project/ -type f -exec chmod 664 {} \;

  4. Change your project directory permissions to 775:

    sudo find /var/www/your-project/ -type d -exec chmod 775 {} \;

  5. Set ACL permissions to make sure new files created by the webserver have correct permissions:

    sudo setfacl -Rdm g:www-data:rw /var/www/your-project/bootstrap/cache/
    sudo setfacl -Rdm g:www-data:rw /var/www/your-project/storage/logs/
    sudo setfacl -Rdm g:www-data:rw /var/www/your-project/storage/framework/
    sudo setfacl -Rdm g:www-data:rw /var/www/your-project/storage/app/
    


Answered By - LobsterBaz
Answer Checked By - Cary Denson (WPSolving Admin)