两种配置方式

如何在nginx配置多个vue项目?第一种是使用不同的端口,既配置多个server即可。第二种是同一个端口,既在一个server里面配置多个vue项目。

使用多个server配置多个vue项目(使用多个端口)

这个方式最简单,将第一份server配置拷贝一下,稍微调整一下就可以了,示例如下:

server {
    listen       9001;
    server_name  localhost;
	# 这个是第一个vue项目 页面访问地址 http://ip:9001/one
    location /one {
         root   /home/project/dist/;
         index  index.html index.htm;
         try_files $uri $uri/ /index.html; # 防止页面刷新404
    }
    ... ...
}

server {
    listen       9002;
    server_name  subhost;
	# 这个是第二个vue项目 页面访问地址 http://ip:9002/two
    location  /two {
         root   /home/sub_project/dist/;
         index   index.html;
         try_files $uri $uri/ /index.html; # 防止页面刷新404
    }
    ... ...
}

在一个server配置多个项目(共用一个端口)

多个端口,只需要调整nginx配置,若使用同一个端口,则需要稍微调整一下vue打包配置。

  • 调整子项目vue.config.js文件的publicPath属性值
... ...
module.exports = {
  publicPath: '/sub', # 非主项目,这边要修改一下指定路径
  outputDir: 'dist',  # 这个不用调整
  assetsDir: 'static',# 这个也不需要调整
  ... ...
}
  • 调整子项目router配置的创建路由配置
... ...
const createRouter = () => new Router({
  base: '/sub', # 调整这里,路径跟publicPath保持一致即可
  mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: routers 
})
... ...
  • 调整完毕后,直接执行build打包命令,可以发现index.html引入js路径增加了/sub
... ...
<script type="text/javascript" src="/sub/static/js/chunk-vendors.js"></script>
<script type="text/javascript" src="/sub/static/js/app.js"></script>
... ...
  • 最后,调整nginx的server配置
server {
    listen       9001;
    server_name  localhost;
	# 这个是第一个vue项目 页面访问地址 http://ip:9001
    location / {
         root   /home/project/dist/;
         index  index.html index.htm;
         try_files $uri $uri/ /index.html;
    }
    # 这个是第二个vue项目 页面访问地址 http://ip:9001/sub
    location  /sub {
         alias   /home/sub_project/dist/;
         index   index.html;
         try_files $uri $uri/ /index.html;
    }
}
Logo

前往低代码交流专区

更多推荐