在 macos 上配置 nginx 虚拟主机需正确设置 server 块、确保主配置通过 include 加载、验证路径权限并用 nginx -t 测试,最后 sudo nginx -s reload 生效。

在 macOS 上用 Nginx 配置虚拟主机(Virtual Host),核心就是写好 server 块并确保它被主配置加载。和 Linux 类似,但 macOS 的默认安装路径、权限管理、启动方式略有不同,容易卡在“配置写了却没生效”这一步。
确认 Nginx 安装与配置路径
macOS 常用 Homebrew 安装 Nginx:
- 安装命令:
brew install nginx - 主配置文件默认位置:
/opt/homebrew/etc/nginx/nginx.conf(Apple Silicon)或/usr/local/etc/nginx/nginx.conf(Intel) - 建议把虚拟主机配置单独拆出,例如放在
/opt/homebrew/etc/nginx/servers/目录下,再通过include引入
检查是否加载成功:运行 nginx -t,提示 syntax is ok 且 test is successful 才算路径和语法都对。
写一个基础 server 块(支持本地域名)
比如想让 local.test 指向 /Users/yourname/Sites/test 目录:
- 先修改系统 hosts:
sudo nano /etc/hosts,加一行127.0.0.1 local.test - 新建
/opt/homebrew/etc/nginx/servers/local.test.conf,内容如下:
server {
listen 80;
server_name local.test;
root /Users/yourname/Sites/test;
index index.html index.php;
<pre class="brush:php;toolbar:false;">location / {
try_files $uri $uri/ /index.html;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # 需搭配 PHP-FPM
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}}
部署和使用军舰的 macOS Automator 自动化服务集合。包含 5 个实用工作流:PDF转JPG、PNG重命名并转JPG、图像拼接、解压RAR、顺序命名图像文件。一键安装所有服务到 ~/Library/Services/ 目录。使用场景:(1) "安装我的自动化服务",(2) "部署所有 Automato...
注意:root 路径必须真实存在且 Nginx 进程有读取权限(通常属于 www 或 _www 用户);PHP 支持需额外启用 PHP-FPM。
启用配置并重启 Nginx
确保主配置中包含该文件:
- 打开
nginx.conf,在http { ... }块内加入:include servers/*.conf; - 重载配置:
sudo nginx -s reload(不是restart,避免中断服务) - 若提示 “permission denied”,常见原因是目录无执行权限(
x权限),对父目录逐级执行:chmod +x /Users/yourname /Users/yourname/Sites /Users/yourname/Sites/test
调试技巧:快速定位问题
配置不生效?按顺序查这几项:
-
nginx -T:输出完整生效的配置(含所有 include),确认你的 server 块确实在里面 -
sudo tail -f /opt/homebrew/var/log/nginx/error.log:看错误日志,常见如 “no such file or directory” 是路径错,“permission denied” 是权限不足 - 浏览器访问时用
curl -I http://local.test看响应头,确认是否真由 Nginx 返回(而非跳转到其他服务) - 用
ps aux | grep nginx确认 master 进程用户是root,worker 进程用户是www(或你配置的用户)
不复杂但容易忽略细节,配一次理清路径、权限、加载逻辑,后面加多个站点就很快了。










