温馨提示×

centos laravel权限如何设置

小樊
45
2026-09-21 03:00:37
栏目: 智能运维

CentOS 上部署 Laravel 时,权限问题主要集中在 storage、bootstrap/cache 目录以及 PHP 运行用户(nginx/php-fpm) 的权限配置。下面是一套标准、安全的做法


一、确认运行用户

1. 查看 Web 服务用户

通常:

  • Nginx + PHP-FPMnginxphp-fpm
  • Apacheapache
ps aux | grep php-fpm
ps aux | grep nginx

一般 CentOS 下 PHP-FPM 用户是:

www-data  # Ubuntu
apache    # CentOS Apache
nginx     # CentOS Nginx(常见)

二、Laravel 目录权限设置(推荐方式)

假设:

  • 项目目录:/var/www/laravel
  • Web 用户:nginx

1. 设置目录所有者

chown -R nginx:nginx /var/www/laravel

如果是开发环境,也可以是你自己 + web 用户:

chown -R youruser:nginx /var/www/laravel

2. 设置目录和文件权限

# 目录 755
find /var/www/laravel -type d -exec chmod 755 {} \;

# 文件 644
find /var/www/laravel -type f -exec chmod 644 {} \;

3. 必须可写目录(重点)

chmod -R 775 storage
chmod -R 775 bootstrap/cache

并确保属主是 web 用户:

chown -R nginx:nginx storage bootstrap/cache

三、SELinux 设置(CentOS 特有,很重要)

CentOS 默认开启 SELinux,否则会 403 / 500。

1. 查看状态

getenforce

2. 给 Web 目录设置 httpd 权限

chcon -R -t httpd_sys_content_t /var/www/laravel
chcon -R -t httpd_sys_rw_content_t /var/www/laravel/storage
chcon -R -t httpd_sys_rw_content_t /var/www/laravel/bootstrap/cache

3. 永久生效(推荐)

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/laravel/storage(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/laravel/bootstrap/cache(/.*)?"
restorecon -Rv /var/www/laravel

四、Nginx 配置示例(权限相关)

server {
    listen 80;
    server_name example.com;
    root /var/www/laravel/public;

    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass   unix:/run/php-fpm/www.sock;
        fastcgi_index  index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

五、常见错误排查

1. storage/logs/laravel.log Permission denied

✅ storage 没写权限 / SELinux 没开

2. 页面 500 但没日志

✅ 检查 bootstrap/cache

3. The stream or file could not be opened

✅ 权限 + SELinux 双重检查


六、开发环境快速方案(不推荐生产)

chmod -R 777 storage bootstrap/cache

⚠️ 仅测试用,生产环境禁止


如果你愿意,可以告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Nginx 还是 Apache
  • PHP 版本

我可以给你完全对应的命令

0