使用 Nginx 在 macOS 上本地部署 Vue 项目,供局域网访问
🚧 背景
公司没有专门的测试环境,产品同事需要频繁验证多个 Vue 项目的前端页面。但:
- 各项目使用不同 Node 版本,切换环境非常麻烦
- 缺少标准的统一部署方式
于是我决定使用 Nginx 启动本地 HTTP 服务 ,部署 Vue 打包产物并暴露端口,供局域网中的其他设备访问。
1️⃣ 安装 Nginx(已通过 Homebrew)
你使用 Homebrew 安装 Nginx:
1
brew install nginx
2️⃣ 找到 nginx.conf 配置路径
使用以下命令检查配置并查看路径:
1
nginx -t
输出示例:
1
2
nginx: the configuration file /opt/homebrew/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /opt/homebrew/etc/nginx/nginx.conf test is successful
记录下该路径:
📌 /opt/homebrew/etc/nginx/nginx.conf
3️⃣ 替换配置文件(使用软链接)
如果项目中已经准备了自定义的配置文件,比如:
/Users/mac/code/work-company/plugins/nginx-conf/nginx.conf
可用软链接替换默认配置:
1
sudo ln -sf /Users/mac/code/work-company/plugins/nginx-conf/nginx.conf /opt/homebrew/etc/nginx/nginx.conf
如需取消链接:
1
sudo rm /opt/homebrew/etc/nginx/nginx.conf
4️⃣ 示例配置(监听 8080,适合本地开发)
以下配置新增了一个 server
块,用于监听端口 8080,服务静态资源,并将部分请求代理到后端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 8080;
server_name localhost; # 或 0.0.0.0(允许其他设备访问)
root /Users/mac/code/work-company/dist;
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
}
location /industry-web {
proxy_pass http://192.168.10.132:8002/industry-web;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
📌 配置说明:
listen 8080
:使用非特权端口,无需 sudo 启动root ...
:指向你的 Vue 打包产物目录location /
:支持 Vue 的 history 模式路由proxy_pass
:将接口请求转发到后端服务server_name
:用localhost
:仅本机访问
💡 如何集成到原始配置?
你无需改动其他配置,只需:
- 找到 nginx.conf 的
http {}
块 - 在里面 追加一个新的
server
块 (如上所示)
如果你有多个项目,可以添加多个不同端口的 server
块,一套配置搞定。
其他内容
Nginx 常用命令
命令 | 说明 |
---|---|
sudo nginx -t |
检查配置语法 |
sudo nginx 或 brew services start nginx |
启动服务 |
sudo nginx -s reload |
重载配置(不会中断连接) |
sudo nginx -s stop |
强制停止 |
sudo nginx -s quit |
优雅退出(等当前请求处理完) |
brew services stop nginx |
停止后台服务(brew 管理方式) |
sudo 与非 sudo 启动冲突说明
启动方式 | 是否需要 sudo | 说明 |
---|---|---|
sudo nginx | ✅ 是 | 启用 root 权限,才能监听 80、443 等端口 |
nginx(无 sudo) | ✅ 仅在端口 ≥ 1024 时可用 | 推荐用于开发(例如 8080、5500) |
brew services start nginx | ✅ | 后台守护进程,由系统管理,统一权限 |
📌 注意 :不要混用 sudo nginx
和非 sudo 命令启动。否则会导致权限冲突、无法 reload 或停止进程等问题。
✅ 总结
步骤 | 操作 |
---|---|
✅ 安装 | brew install nginx |
✅ 查找配置 | nginx -t 查看配置路径 |
✅ 替换配置 | 使用软链接替换 nginx.conf |
✅ 写配置 | 添加监听端口、自定义路径和代理 |
✅ 启动服务 | 使用 sudo nginx 或 brew services 启动服务 |