vue项目nginx部署在子目录

前提

vue项目:vue版本 2.6.10,  用vue-cli一键生成的vue项目,vue.config.js自动集成了的,为了项目的个别不同配置,另在项目根目录下新建了vue.config.js。

以下我们假设 子目录 是 /my-app/。

一、vue.config.js 文件中作出相应改动:

1 // 项目部署基础
2 // 默认情况下,我们假设你的应用将被部署在域的根目录下,
3 // 例如:https://www.my-app.com/
4 // 默认:'/'
5 // 如果您的应用程序部署在子路径中,则需要在这指定子路径
6 // 例如:https://www.xxxx.com/my-app/
7 // 需要将它改为'/my-app/'
8 
9 const BASE_URL = process.env.NODE_ENV === 'production' ? '/my-app/' : '/';

二、路由处做修改,添加base。

1 const router = new Router({
2   mode: 'history',
3   base: 'my-app',
4   routes: routes
5 });

至此,vue项目的修改就OK了,dev环境下运行项目,就可以看到 路由中已经添加了/my-app/前缀。localhost:8080/my-app/home。

三、nginx 配置:    server {        listen 8888;#默认端口是80,如果端口没被占用可以不用修改

        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        root        E:xxxxxx-webdist; #vue项目的打包后的dist

     # 配置一级目录项目 location
/ {
try_files $uri $uri
/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404 index index.html index.htm; } #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件 #因此需要rewrite到index.html中,然后交给路由在处理请求资源       
      
      # 配置二级目录/my-app/ location
/my-app/ { alias
E:xxxxxx-webdist; #vue项目的打包后的dist
       index index.html index.htm; 
      try_files $uri $uri
/ index.html;
    }
    location @router {
      rewrite
^.*$ /index.html last;
    }
}

配置好之后,重启nginx即可。

原文地址:https://www.cnblogs.com/ordinary-yolanda/p/13495040.html