nginx同域名下多个vue项目

162 阅读1分钟

nginx同域名下多个vue项目共享缓存

本地两个项目

主项目 http://localhost:8080/#/

子项目 http://localhost:8081/#/

一。先确保本地安装了nginx

二。对另一个项目的路由和打包配置进行处理,目标是最终的路由指向做区别。

添加base:"/son",(base:"/son/",) 配置来做区别

1.路由 router.js

const router = createRouter({

  history: createWebHistory(import.meta.env.BASE_URL),

  base:"/son",

  routes: [

    {

      path: '/',

      name: 'home',

      component: HomeView

    },

    {

      path: '/about',

      name: 'about',

      component: () => import('../views/AboutView.vue')

    }

  ]

})

2.vite.config.js 打包配置

// https://vitejs.dev/config/

export default defineConfig({

  plugins: [vue()],

  base:"/son",

  resolve: {

    alias: {

      '@': fileURLToPath(new URL('./src', import.meta.url))

    }

  }

})

三。两个项目分别打包npm run build,将打包的文件放到nginx的html里面

新建dist和dist2两个文件夹,主项目打包文件放到dist里面,子项目打包文件放到dist2里面

截屏2024-07-06 下午4.16.14.png

四。配置nginx

1.找到nginx目录 C:\Esoftware\nginx-1.24.0\conf下面的 nginx.conf文件

server {

        listen       18001;//端口号默认80 可以不修改

        server_name  127.0.0.1;//localhost域名 可以不修改

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

       location  ^~ / {

            alias   html/dist/;

            index  index.html index.htm;

        }

        location ^~ /son/ {

            alias   html/dist2/;

            index  index.html index.htm;

        }

2.如果本地项目有接口调用则需要配置 proxy_pass http://localhost:8080 本地项目启动。不然接口会报404错误。

server {

        listen       18001;

        server_name  127.0.0.1;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

       location  ^~ / {

            alias   html/dist/;

            index  index.html index.htm;

            try_files $uri/ /index.html;#配置vue路由映射,不然无法通过路由访问

             proxy_pass http://localhost:8080;    # 服务器地址1

        }

        location ^~ /son/ {

            alias   html/dist2/;

            index  index.html index.htm;

            try_files $uri/ /index.html;#配置vue路由映射,不然无法通过路由访问

        }

3.nginx启动

在电脑 C:\Esoftware\nginx-1.24.0 路径下cmd 弹出命令面板

输入 start nginx

4.如果配置文件有修改,则需要更新

输入 nginx -s reload

注意。配置了 proxy_pass http://localhost:8080 就相当于项目直接访问 http://localhost:8080项目而不是打包的项目。

可以直接本地修改内容查看。

五。然后可以查看访问结果

http://127.0.0.1:18001/

http://127.0.0.1:18001/son/

可以看到localStorage 两项目都能使用了。