插件窝 干货文章 nginx如何配置多个前端项目

nginx如何配置多个前端项目

index project 配置 location 781    来源:    2025-04-22

Nginx配置多个前端项目指南

在Nginx中配置多个前端项目可以通过以下几种方式实现,我将详细介绍每种方法。

方法1:基于不同端口的配置

server {
    listen 8080;
    server_name localhost;

    location / {
        root /path/to/project1;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

server {
    listen 8081;
    server_name localhost;

    location / {
        root /path/to/project2;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

方法2:基于不同域名的配置

server {
    listen 80;
    server_name project1.example.com;

    location / {
        root /path/to/project1;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

server {
    listen 80;
    server_name project2.example.com;

    location / {
        root /path/to/project2;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

方法3:基于URL路径的配置(推荐)

server {
    listen 80;
    server_name example.com;

    location /project1/ {
        alias /path/to/project1/;
        index index.html;
        try_files $uri $uri/ /project1/index.html;
    }

    location /project2/ {
        alias /path/to/project2/;
        index index.html;
        try_files $uri $uri/ /project2/index.html;
    }

    # 可选:设置默认项目
    location / {
        root /path/to/default-project;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

方法4:使用正则表达式匹配

server {
    listen 80;
    server_name example.com;

    location ~ ^/(project1|app1)(/|$) {
        alias /path/to/project1/;
        index index.html;
        try_files $uri $uri/ /project1/index.html;
    }

    location ~ ^/(project2|app2)(/|$) {
        alias /path/to/project2/;
        index index.html;
        try_files $uri $uri/ /project2/index.html;
    }
}

重要注意事项

  1. 路径配置区别

    • 使用root时,Nginx会将location路径附加到root路径后
    • 使用alias时,location路径会被alias路径完全替换
  2. 单页应用(SPA)配置

    try_files $uri $uri/ /index.html;
    

    这行配置对于Vue、React等前端框架非常重要,确保路由能正确工作

  3. 静态资源缓存: 可以添加缓存控制:

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
       expires 1y;
       add_header Cache-Control "public";
    }
    
  4. 配置验证: 修改配置后,使用以下命令检查并重载:

    nginx -t  # 测试配置
    nginx -s reload  # 重载配置
    
  5. 跨域问题: 如果需要API代理,可以添加:

    location /api/ {
       proxy_pass http://api-server/;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
    }
    

选择哪种配置方式取决于你的具体需求,基于URL路径的配置通常是最灵活和常用的方案。