Nginx-支持单域名多-Vue-服务配置备忘

16次阅读

共计 643 个字符,预计需要花费 2 分钟才能阅读完成。

最近开发时,遇到需要使用同一域名承载多个前端项目的场景,具体需求如下:

  1. /v2 访问新版本前端项目
  2. /api 访问后端 Spring Boot 接口服务
  3. / 访问默认前端项目

1. Nginx 配置内容

server {
    listen       80;
    listen       [::]:80;
    server_name  _;

    server_name_in_redirect off;
    proxy_set_header Host $host;

    location /api {proxy_pass http://0.0.0.0:0000;}

    location / {
        index  index.html;
        root /path/to/main/web/app;
    }

    location /v2 {
        index  index.html;
        root /path/to/v2/web/app;
    }
}

2. 修改 publicPath 配置

仅仅通过上述配置,在访问新版前端时,会遇到资源文件无法找到的问题。

此时,可以通过对新版前端 vue.config.js 文件中的 publicPath 进行配置,以规避这一问题(注:该方法仅适用于 Vue-Cli 3.x 构建的项目):

module.exports = {
    ...
    
    publicPath: '/v2/',
    
    ...
};

参考链接

  1. Understanding the difference between the root and alias directives in Nginx;
  2. Can’t get two single page applications to run together on one server using nginx;

正文完
 0