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:\x\xx\xxx-web\dist; #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:\x\xx\xxx-web\dist; #vue項目的打包后的dist
       index index.html index.htm; 
      try_files $uri $uri
/ index.html;
    }
    location @router {
      rewrite
^.*$ /index.html last;
    }
}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM