Vue-cli項目部署到Nginx


項目環境:

0. Nginx使用

以windows版為例,下載niginx壓縮包並解壓到任意目錄,雙擊nginx.exe,在瀏覽器中訪問http://localhost,如果出現Welcome to nginx!頁面則說明成功。

nginx常用命令如下:

nginx -h		# 打開幫助
nginx -t		# 檢查配置文件是否正確

# 以下命令均要先啟動nginx才能執行
nginx -s stop	# 停止
nginx -s quit	# 退出
nginx -s reopen	# 重新啟動(注意不會重新讀取配置文件)
nginx -s reload	# 重新讀取配置文件

1. 部署項目到Nginx根目錄

對於vue-cli創建的項目,修改vue.config.js文件(位於項目根目錄下,沒有的話自行創建):

module.exports = {
  // 開發環境中使用的端口
  devServer: {
    port: 8001
  },
  // 取消生成map文件(map文件可以准確的輸出是哪一行哪一列有錯)
  productionSourceMap: false,
  // 開發環境和部署環境的路徑
  publicPath: process.env.NODE_ENV === 'production'
    ? '/'
    : '/my/',
  configureWebpack: (config) => {
    // 增加 iview-loader
    config.module.rules[0].use.push({
      loader: 'iview-loader',
      options: {
        prefix: false
      }
    })
    // 在命令行使用 vue inspect > o.js 可以檢查修改后的webpack配置文件
  }
}

在vue項目根目錄中使用命令npm run build創建輸出文件,將dist文件夾下的所有內容復制到nginx目錄下的webapp/內(沒有的話自行創建)。

修改nginx目錄中的conf/nginx.conf文件,在 http -> server 節點中,修改location節的內容:

location / {
    root   webapp;
    index  index.html index.htm;
}

在nginx根目錄使用命令nginx -s reload即可在瀏覽器中通過http://localhost訪問項目。

2. 多個項目部署到Nginx

有時一個Nginx中放了好幾個子項目,需要將不同的項目通過不同的路徑來訪問。

對於項目1而言,修改vue.config.js文件的publicPath

publicPath: '/vue1/'

對於項目2而言,修改vue.config.js文件的publicPath

publicPath: '/vue2/'

分別在vue項目根目錄中使用命令npm run build創建輸出文件,將dist文件夾下的所有內容復制到nginx目錄下的webapp/vue1webapp/vue2內(沒有的話自行創建)。

修改nginx目錄中的conf/nginx.conf文件,在 http -> server 節點中,修改location節的內容:

location /vue1 {
    root   webapp;
    index  index.html index.htm;
}

location /vue2 {
    root   webapp;
    index  index.html index.htm;
}

在nginx根目錄使用命令nginx -s reload即可在瀏覽器中通過http://localhost/vue1http://localhost/vue2訪問項目1、項目2。

3. 端口代理

當前后端項目分別部署在同一台機器上時,由於無法使用相同的端口,故后端一般會將端口號設置成不同的值(例如8080),但是當前端向后端請求資源時還要加上端口號,未免顯得麻煩,故利用可以nginx將前端的指定路徑代理到后端的8080端口上。

conf/nginx.conf文件中增加location

location /api {
    proxy_pass http://localhost:8080/api;
}

這樣,當前端訪問/api路徑時,實際上訪問的是http://localhost:8080/api路徑。


免責聲明!

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



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