Mac部署PHP动态项目应避开系统自带方案,因其PHP版本旧(≤8.1)、缺mod_rewrite等关键扩展;推荐用Homebrew安装新版PHP并启用intl、mbstring、opcache,配置Nginx匹配PHP-FPM监听地址,设置URL重写规则指向public目录,并修正PHP-FPM用户权限。

Mac 上部署 PHP 动态项目,别直接套用“系统自带 Apache + PHP”方案——它默认不支持 mod_rewrite、intl、mbstring 等现代框架必需扩展,且 PHP 版本普遍停留在 8.1 以下(macOS Sonoma 14.7 默认为 PHP 8.1.2,Sequoia 15 已移除系统 PHP),实际跑 Laravel/ThinkPHP/CakePHP 会卡在路由重写或字符编码上。
确认当前 PHP 是否可用且版本达标
终端执行 php -v,如果报错 command not found: php 或显示 PHP 8.1.2 及更旧版本,说明不能直接依赖系统 PHP。Homebrew 安装的 PHP 路径通常为 /opt/homebrew/bin/php(Apple Silicon)或 /usr/local/bin/php(Intel),需确保 which php 返回的是这个路径。若不是,检查 shell 配置文件(如 ~/.zshrc)是否已按 Homebrew 提示追加了 export PATH="/opt/homebrew/bin:$PATH" 并执行 source ~/.zshrc。
启用关键扩展:intl、mbstring、opcache
动态项目(尤其多语言或 ORM 场景)强依赖 intl(国际化)、mbstring(多字节字符串处理)、opcache(性能加速)。Homebrew 安装 PHP 后,这些扩展默认编译进 PHP,但需在 php.ini 中显式启用:
- 找到配置文件路径:
php --ini输出中的 “Loaded Configuration File”,通常是/opt/homebrew/etc/php/8.3/php.ini(版本号依安装而定) - 编辑该文件,取消以下三行的注释(删除开头分号):
extension=intlextension=mbstringzend_extension=opcache - 重启 PHP-FPM:
brew services restart php@8.3(注意替换为你安装的版本) - 验证:
php -m | grep -E '^(intl|mbstring|opcache)$'应全部输出
Nginx 配置必须匹配 PHP-FPM 监听地址
常见错误是 Nginx 的 fastcgi_pass 指向错误端口或 socket,导致 502 Bad Gateway。Homebrew 安装的 PHP-FPM 默认监听 127.0.0.1:9000(TCP)或 /opt/homebrew/var/run/php-fpm.sock(Unix socket),需与 Nginx 配置严格一致:
立即学习“PHP免费学习笔记(深入)”;
- 检查 PHP-FPM 实际监听方式:
grep -E "^(listen|listen.allowed_clients)" /opt/homebrew/etc/php/8.3/php-fpm.d/www.conf - 若为
listen = 127.0.0.1:9000,Nginx 的location ~ \.php$块中必须写:fastcgi_pass 127.0.0.1:9000; - 若为
listen = /opt/homebrew/var/run/php-fpm.sock,则写:fastcgi_pass unix:/opt/homebrew/var/run/php-fpm.sock; - 务必同步设置
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;,漏掉这行会导致 PHP 找不到脚本文件
项目入口与 URL 重写必须由 Web 服务器接管
ThinkPHP/Laravel 等框架要求所有请求经由 public/index.php 入口,且依赖重写隐藏 index.php。Apache 需启用 mod_rewrite 并在项目目录下放 .htaccess;Nginx 则必须在 server 块内显式配置重写规则:
- 对于 Laravel 项目,Nginx 推荐规则:
location / {<br> try_files $uri $uri/ /index.php?$query_string;<br>} - 确保
root指向项目public目录,而非整个项目根目录(否则app/、config/等敏感目录可能被直接访问) - 权限问题常被忽略:Nginx worker 进程用户(默认
www-data或_www)需对项目目录有读取+执行权限(chmod 755目录,644文件),storage和bootstrap/cache还需写入权限
最易被跳过的环节是 PHP-FPM 的 user 和 group 配置——它默认以 _www 用户运行,但你的项目文件若属当前用户(如 yourname:staff),且未开放组读权限,就会出现“file not found”或空白页。打开 /opt/homebrew/etc/php/8.3/php-fpm.d/www.conf,把 user 和 group 改成你的用户名和 staff 组,再重启服务。



















