Linux部署PHP框架需改三处:document_root指向public目录、storage和bootstrap/cache设Web用户可写、.env中APP_ENV=production且APP_DEBUG=false。

PHP框架在Linux部署时必须改的配置项
绝大多数跨平台部署失败,根源不在代码本身,而在于框架默认配置假定的是开发环境(如 Windows 或 macOS),直接扔到 Linux 上跑会因路径、权限、扩展缺失直接报错。关键要改三处:document_root、public 目录暴露方式、以及 storage 和 bootstrap/cache 的写权限。
-
document_root必须指向框架的public子目录(例如 Nginx 的root /var/www/myapp/public;),不是项目根目录 - Laravel/ThinkPHP 等框架的
storage和bootstrap/cache目录需由 Web 服务器用户(如www-data或nginx)可写:sudo chown -R www-data:www-data storage bootstrap/cache - 确认
APP_ENV和APP_DEBUG在.env中设为production和false,否则调试信息泄露且性能下降
Linux下常被忽略的PHP扩展与模块依赖
Windows WAMP/XAMPP 自带一堆扩展,但 Linux 发行版默认只装最精简的 PHP,框架运行时会静默失败或抛出 Class not found 错误——比如 Laravel 的 mbstring、xml、curl、openssl、pdo_mysql(或 pdo_pgsql)缺一不可。
- Debian/Ubuntu:运行
sudo apt install php-mbstring php-xml php-curl php-zip php-gd php-bcmath php-opcache php-pdo php-mysql - CentOS/RHEL:用
sudo yum install php-mbstring php-xml php-curl php-zip php-gd php-bcmath php-opcache php-pdo php-mysqlnd - 改完别忘了重启 Web 服务:
sudo systemctl restart nginx或sudo systemctl restart apache2
为什么本地能跑,Linux上访问/public/index.php就404?
这不是框架问题,是 Web 服务器没正确启用 URL 重写(即隐藏 index.php)。Linux 下 Nginx 默认不处理 PATH_INFO,Apache 则可能未开启 mod_rewrite 或站点未允许 .htaccess 覆盖。
- Nginx:在 server 块中必须包含
try_files $uri $uri/ /index.php?$query_string;,且确保fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;正确(不是$document_root) - Apache:确认
a2enmod rewrite已执行,并在虚拟主机配置中设置AllowOverride All(不能是None) - 验证方法:临时把
public/index.php改成phpinfo();,能打开说明 Web 服务通,打不开说明路径或权限根本没配对
跨平台部署时环境变量和路径的硬编码陷阱
很多开发者在代码里写死 C:\xampp\htdocs\... 或 /Users/me/project/...,或者用 __DIR__ 拼接出绝对路径再 require,这类逻辑在 Linux 部署时必然崩。框架自身已提供抽象层,不该绕过。
立即学习“PHP免费学习笔记(深入)”;
- 永远用框架提供的路径辅助函数,如 Laravel 的
base_path()、public_path()、storage_path();ThinkPHP 的ROOT_PATH、PUBLIC_PATH -
.env文件不要提交进 Git,Linux 部署时重新生成,尤其注意DB_HOST不能写127.0.0.1(Docker 场景下应为容器名) - 日志写入失败?检查
storage/logs是否被 SELinux 或 systemd-private 临时目录机制拦截(CentOS/RHEL 常见),可用ls -Z storage/logs查看上下文
最麻烦的往往不是改哪几行,而是改完没清缓存——Laravel 要 php artisan config:clear 和 php artisan cache:clear,ThinkPHP 要删 runtime/cache 全部内容。这些步骤漏掉,前面全白调。











