vue部署到nginx

nginx

1、安裝nginx
2、到nginx的安裝目錄下使用 start nginx啟動nginx服務(wù)
3、nginx的主配置文件在/conf/nginx.conf
4、修改vue項目里的vue.config.js的配置文件

  • 添加publicPath選項,根據(jù)你需要部署的路徑來進行設(shè)置。
// 值根據(jù)你所需要部署的項目路徑來,如果是根目錄,只需要修改成/即可
module.exports = {
  publicPath: '/testWeb/'
}

5、打包部署文件 npm
6、將打包部署后的文件放在nginx/html目錄下
7、修改nginx的配置文件

// 同一個端口部兩套vue項目,通過根路徑區(qū)分
// 第一套項目,publicPath:'/'
location / {
     root   html/dist; // 指向vue目錄
     index  index.html index.htm; // index指向 html/dist/index文件
     try_files $uri $uri/ /index.html;
}
// 第二套項目,publicPath: '/testWeb/'
location /testWeb { // 這里的testWeb與4中所配置的路徑一致
    alias html/testWeb;// 指向vue目錄
    index index.html index.html;// index指向html/testWeb/index.html文件
    try_files $uri $uri/ /testWeb/index.html; // 當(dāng)找不到文件的時候,就會重定向到這個文件下
}
  • try_files 是用來解決vue項目在nginx部署,刷新404的問題(因為文件路徑并非真實存在的,需要重定向到頁面里)

try_files:當(dāng)用戶請求 http://localhost/example 時,這里的 uri 就是 /example。 try_files 會到硬盤里嘗試找這個文件。如果存在名為 /root/example (其中 root 是項目代碼安裝目錄)的文件,就直接把這個文件的內(nèi)容發(fā)送給用戶。 顯然,目錄中沒有叫 example 的文件。然后就看uri/,增加了一個 /,也就是看有沒有名為 /$root/example/ 的目錄。
又找不到,就會 fall back 到 try_files 的最后一個選項 /index.html,發(fā)起一個內(nèi)部 “子請求”,也就是相當(dāng)于 nginx 發(fā)起一個 HTTP 請求到 http://localhost/index.html

8、測試配置文件nginx -t
9、重啟,載入新的配置文件nginx -s reload
10、此時打開localhost/testWeb就能看到頁面了

tip

  • rootalias的區(qū)別:
    root的處理結(jié)果是:root路徑+location路徑
    alias的處理結(jié)果是:使用alias路徑替換location路徑
    舉個例子:
server {
    listen              8081;
    server_name         localhost;
    location /test {
         root   html;  // 此時訪問localhost:8081/test 相當(dāng)于訪問 html/test/index.html
         index  index.html index.htm;
    }
    location /test {
        alias    html/; // 此時訪問localhost:8081/test 相當(dāng)于訪問 html/index.html
        index  index.html index.htm;
    }
    location /test {
        alias    html/test/; // 此時訪問localhost:8081/test 相當(dāng)于訪問 html/test/index.html
        index  index.html index.htm;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容