Nginx部署多前端项目的三种配置方案

在Nginx中部署多个前端项目时,需要合理配置server和location块以实现资源隔离和路由分发。本文介绍三种典型方案,涵盖不同场景需求。

方案1:基于不同域名部署

nginx配置信息

  1. server {
  2. listen 80;
  3. server_name app1.example.com;
  4. root /var/www/app1/dist;
  5. index index.html;
  6. location / {
  7. try_files $uri $uri/ /index.html;
  8. }
  9. }
  10. server {
  11. listen 80;
  12. server_name app2.example.com;
  13. root /var/www/app2/dist;
  14. index index.html;
  15. location / {
  16. try_files $uri $uri/ /index.html;
  17. }
  18. }

配置要点

  1. 每个server块绑定独立域名
  2. root指令指定不同前端构建目录
  3. try_files处理单页应用路由

适用场景

  • 拥有独立域名的生产环境
  • 需要完全隔离的静态资源

方案2:基于不同端口部署

nginx配置信息

  1. server {
  2. listen 8080;
  3. server_name localhost;
  4. root /var/www/app1/dist;
  5. index index.html;
  6. location / {
  7. try_files $uri $uri/ /index.html;
  8. }
  9. }
  10. server {
  11. listen 8081;
  12. server_name localhost;
  13. root /var/www/app2/dist;
  14. index index.html;
  15. location / {
  16. try_files $uri $uri/ /index.html;
  17. }
  18. }

配置要点

  1. 通过不同端口区分应用
  2. 保持server_name一致
  3. 需在访问时显式指定端口

适用场景

  • 本地开发测试环境
  • 临时部署需求

方案3:基于路径区分部署

nginx配置信息

  1. server {
  2. listen 80;
  3. server_name example.com;
  4. location /app1 {
  5. alias /var/www/app1/dist;
  6. index index.html;
  7. try_files $uri $uri/ /app1/index.html;
  8. }
  9. location /app2 {
  10. alias /var/www/app2/dist;
  11. index index.html;
  12. try_files $uri $uri/ /app2/index.html;
  13. }
  14. }

配置要点

  1. 使用alias而非root指令
  2. try_files需包含路径前缀
  3. 前端需配置publicPath(如Vue的publicPath: ‘/app1/‘)

适用场景

  • 二级目录部署需求
  • 共享域名的多应用场景

方案对比

方案 优点 缺点 适用场景
域名 资源完全隔离 需DNS配置 生产环境
端口 配置简单 访问需带端口 本地测试
路径 共享域名 需前端配合 二级部署