使用 Nginx 在 macOS 上本地部署前端项目,供局域网访问

129 阅读3分钟

使用 Nginx 在 macOS 上本地部署 Vue 项目,供局域网访问

🚧 背景

作为一名前端,公司没有专门的测试环境,产品同事需要频繁验证多个 Vue 项目的前端页面。但:

  • 各项目使用不同 Node 版本,切换环境非常麻烦。(使用nvm可以解决这个问题)
  • 缺少标准的统一部署方式。
  • 每次为同事提供测试环境,启动dev(耗费大量资源)

于是我决定使用 Nginx 启动本地 HTTP 服务 ,部署 Vue 打包产物并暴露端口,供局域网中的其他设备访问。

1️⃣ 安装 Nginx(已通过 Homebrew)

你使用 Homebrew 安装 Nginx:

brew install nginx

2️⃣ 找到 nginx.conf 配置路径

使用以下命令检查配置并查看路径:

nginx -t

输出示例:

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

可用软链接替换默认配置:

sudo ln -sf /Users/mac/code/work-company/plugins/nginx-conf/nginx.conf /opt/homebrew/etc/nginx/nginx.conf

如需取消链接:

sudo rm /opt/homebrew/etc/nginx/nginx.conf

示例配置

以下配置新增了一个 server 块,用于监听端口 8080,服务静态资源,并将部分请求代理到后端:

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 /:支持 history模式路由
  • proxy_pass:将接口请求转发到后端服务
  • server_name:用 localhost:仅本机访问

💡 如何集成到原始配置?

你无需改动其他配置,只需:

  • 找到 nginx.conf 的 http {}
  • 在里面 追加一个新的 server (如上所示)

如果你有多个项目,可以添加多个不同端口的 server 块,一套配置搞定。

其他内容

Nginx 常用命令

命令说明
sudo nginx -t检查配置语法
sudo nginxbrew 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 nginxbrew services启动服务