使用 brew install php nginx 安装后,在终端执行 nginx -t 验证配置无误,随后通过 brew services start nginx 启动服务即可。

检查 Homebrew 环境
确保系统已安装 Homebrew。若未安装,请先运行 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 完成初始化。

Homebrew 是 macOS 下最流行的包管理器,能自动处理 PHP 和 Nginx 的依赖关系。安装完成后,建议先运行 brew update 同步软件源,避免拉取到过期版本导致后续配置冲突。
安装 PHP 与 Nginx
在终端中依次执行安装命令,等待下载编译完成。

// main.go
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/info.php" {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintln(w, "<?php phpinfo(); ?>")
return
}
fmt.Fprint(w, "Hello from Go")
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Server listening on port %s\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
该程序模拟了静态文件服务。当访问 /info.php 时,直接返回 PHP 代码片段用于测试 Nginx 是否正确传递请求。实际部署中,应删除此路由,让 Nginx 直接读取磁盘上的 .php 文件并通过 FastCGI 协议交给 PHP 解释器执行。若页面显示源码而非结果,说明 Nginx 未正确配置 fastcgi_pass 或 PHP-FPM 服务未启动。
brew install php 会安装最新稳定版 PHP,同时包含常用扩展。brew install nginx 安装轻量级 Web 服务器。安装结束后,PHP 默认监听本地端口,Nginx 配置文件位于 /opt/homebrew/etc/nginx/nginx.conf(Apple Silicon)或 /usr/local/etc/nginx/nginx.conf(Intel)。需手动修改 Nginx 配置以支持 PHP-FPM 解析。
配置 Nginx 支持 PHP-FPM
修改 Nginx 配置文件,将 .php 请求转发给 PHP-FPM 进程。
打开 nginx.conf,找到 location ~ \.php$ 块。取消注释并修改 fastcgi_pass 指向 unix:/opt/homebrew/var/run/php-fpm.sock(根据架构调整路径)。保存后执行 sudo nginx -s reload 重载配置。此时访问 localhost 下的 PHP 文件即可正常输出。