温馨提示×

如何在Ubuntu上部署PHP框架

小樊
37
2025-12-06 14:37:43
栏目: 编程语言

在 Ubuntu 上部署 PHP 框架的标准流程

一 环境准备

  • 更新系统并安装基础组件(以 Ubuntu 20.04/22.04 为例):
    • 安装 Web 与语言环境:NginxPHP 8.0+MySQL/MariaDBComposerGit
    • 常用 PHP 扩展:pdo、mbstring、curl、openssl、tokenizer、xml、zip
  • 示例命令:
    • sudo apt update
    • sudo apt install nginx mysql-server php-fpm php-mysql php-cli php-curl php-mbstring php-xml php-zip git composer
  • 建议启用 OPcache 提升性能,并确认 PHP 版本满足目标框架要求(如 Laravel 10/11 需 PHP 8.1+)。

二 部署代码与安装依赖

  • 将项目放置到 /var/www/your-project(示例),使用 Git 或上传压缩包解压:
    • cd /var/www/your-project
  • 安装生产依赖(不装 dev 依赖):
    • composer install --optimize-autoloader --no-dev
  • 框架初始化(以 Laravel 为例):
    • cp .env.example .env
    • php artisan key:generate
    • 编辑 .env 配置数据库与应用密钥
    • php artisan migrate --force(生产谨慎,建议先在预备环境演练)
    • php artisan config:cache && php artisan route:cache(提升性能)

三 配置 Web 服务器与 PHP-FPM

  • 创建 Nginx 站点配置(/etc/nginx/sites-available/your-site):
    • server { listen 80; server_name your-domain.com www.your-domain.com; root /var/www/your-project/public; index index.php index.html; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 按实际 PHP 版本调整 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~ /.ht { deny all; }
    • 启用站点并校验:
      • sudo ln -s /etc/nginx/sites-available/your-site /etc/nginx/sites-enabled
      • sudo nginx -t && sudo systemctl reload nginx
  • 启动 PHP-FPM(按实际版本):
    • sudo systemctl start php8.1-fpm && sudo systemctl enable php8.1-fpm
  • 如使用 Apache,启用 mod_rewrite 并配置虚拟主机指向 public/,同样需将请求转发给 PHP 处理器。

四 文件权限与目录安全

  • 设置目录属主与权限(以 www-data 运行 PHP-FPM 为例):
    • sudo chown -R www-data:www-data /var/www/your-project
    • sudo find /var/www/your-project -type f -exec chmod 644 {} ;
    • sudo find /var/www/your-project -type d -exec chmod 755 {} ;
  • 确保可写目录(以 Laravel 为例):
    • sudo chmod -R 775 /var/www/your-project/storage /var/www/your-project/bootstrap/cache
    • sudo chown -R www-data:www-data /var/www/your-project/storage /var/www/your-project/bootstrap/cache
  • 安全建议:
    • 禁止访问敏感文件:location ~ /.ht { deny all; }
    • 限制上传目录执行 PHP
    • .env 加入 .gitignore,避免泄露密钥

五 生产优化与安全加固

  • PHP 与 Web 服务:
    • 关闭错误显示、开启错误日志:display_errors = Off,log_errors = On
    • 启用并调优 OPcache(生产环境强烈建议)
    • 配置 HTTPS/TLS(如 Let’s Encrypt),强制 HTTP→HTTPS 跳转
  • 运行与维护:
    • 使用进程管理(如 Supervisor)守护队列/长任务
    • 缓存优化:config:cache、route:cache(Laravel),静态资源使用 Nginx 直接服务
    • 日志与监控:应用与 Nginx 错误日志、资源监控与告警
  • 快速验证清单:
    • 访问域名显示首页或健康检查路由
    • 检查 storage/logs/laravel.log 无异常
    • 数据库连接、队列、缓存按预期工作

0