Nginx部署多前端项目的三种配置方案
在Nginx中部署多个前端项目时,需要合理配置server和location块以实现资源隔离和路由分发。本文介绍三种典型方案,涵盖不同场景需求。
方案1:基于不同域名部署
nginx配置信息
server {listen 80;server_name app1.example.com;root /var/www/app1/dist;index index.html;location / {try_files $uri $uri/ /index.html;}}server {listen 80;server_name app2.example.com;root /var/www/app2/dist;index index.html;location / {try_files $uri $uri/ /index.html;}}
配置要点
- 每个server块绑定独立域名
- root指令指定不同前端构建目录
- try_files处理单页应用路由
适用场景
- 拥有独立域名的生产环境
- 需要完全隔离的静态资源
方案2:基于不同端口部署
nginx配置信息
server {listen 8080;server_name localhost;root /var/www/app1/dist;index index.html;location / {try_files $uri $uri/ /index.html;}}server {listen 8081;server_name localhost;root /var/www/app2/dist;index index.html;location / {try_files $uri $uri/ /index.html;}}
配置要点
- 通过不同端口区分应用
- 保持server_name一致
- 需在访问时显式指定端口
适用场景
- 本地开发测试环境
- 临时部署需求
方案3:基于路径区分部署
nginx配置信息
server {listen 80;server_name example.com;location /app1 {alias /var/www/app1/dist;index index.html;try_files $uri $uri/ /app1/index.html;}location /app2 {alias /var/www/app2/dist;index index.html;try_files $uri $uri/ /app2/index.html;}}
配置要点
- 使用alias而非root指令
- try_files需包含路径前缀
- 前端需配置publicPath(如Vue的publicPath: ‘/app1/‘)
适用场景
- 二级目录部署需求
- 共享域名的多应用场景
方案对比
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| 域名 | 资源完全隔离 | 需DNS配置 | 生产环境 |
| 端口 | 配置简单 | 访问需带端口 | 本地测试 |
| 路径 | 共享域名 | 需前端配合 | 二级部署 |
