温馨提示×

linux laravel为何报权限错

小樊
33
2026-09-19 08:34:44
栏目: 智能运维

在 Linux 上运行 Laravel 出现“权限错误(Permission denied)”是非常常见的问题,通常不是代码问题,而是文件/目录权限和属主配置不对

下面按最常见原因 → 解决办法给你梳理。


一、最常见原因:storage / bootstrap/cache 没写权限

Laravel 需要写入:

storage/
bootstrap/cache/

报错示例

The stream or file "/var/www/laravel/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied

解决办法

cd /var/www/your-project
sudo chmod -R 775 storage bootstrap/cache
sudo chown -R www-data:www-data storage bootstrap/cache

www-data 是 Apache/Nginx 的运行用户(不同系统可能是 nginxapache


二、PHP / Web 服务器用户不一致

查看 web 服务用户

ps aux | grep nginx
ps aux | grep apache

查看当前目录属主

ls -l /var/www/your-project

✅ 正确情况:

  • 文件属主:部署用户(如 deploy
  • 写权限组:web 用户(如 www-data

推荐做法(安全)

sudo chown -R deploy:www-data /var/www/your-project
sudo chmod -R 775 storage bootstrap/cache

三、SELinux 导致(CentOS / RHEL 常见)

如果你是 CentOS / Rocky / Alma

ls -Z /var/www/your-project/storage

临时关闭测试

sudo setenforce 0

正确修复(推荐)

sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/your-project/storage(/.*)?"
sudo restorecon -Rv /var/www/your-project/storage

四、Laravel 缓存 / 配置权限问题

执行命令时报权限错:

php artisan cache:clear

解决

sudo chown -R www-data:www-data .
sudo chmod -R 755 .
sudo chmod -R 775 storage bootstrap/cache

五、使用 sudo 导致文件属主变成 root

❌ 错误做法:

sudo php artisan storage:link

✅ 正确:

php artisan storage:link

否则 storage 下文件变成 root,web 无法写。


六、Composer 安装后权限错

sudo composer install

会导致 vendor 属主为 root。

修复

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

七、快速“标准权限脚本”(开发环境)

cd /var/www/your-project
sudo chown -R $USER:www-data .
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod -R 775 storage bootstrap/cache

八、生产环境建议

  • ✅ 不要用 777
  • ✅ 使用 775 + 正确属主
  • ✅ Web 用户只拥有写 storage / bootstrap/cache

如果你愿意

可以把完整报错信息或:

ls -l
ps aux | grep nginx

贴出来,我可以直接帮你精准定位是哪一类权限问题。

0