Vue-cli項目部署到Nginx

項目環境: html

0. Nginx使用

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

nginx經常使用命令以下:vue

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

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

1. 部署項目到Nginx根目錄

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

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

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

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

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

2. 多個項目部署到Nginx

有時一個Nginx中放了好幾個子項目,須要將不一樣的項目經過不一樣的路徑來訪問。npm

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

publicPath: '/vue1/'

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

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訪問項目一、項目2。

3. 端口代理

當先後端項目分別部署在同一臺機器上時,因爲沒法使用相同的端口,故後端通常會將端口號設置成不一樣的值(例如8080),可是當前端向後端請求資源時還要加上端口號,未免顯得麻煩,故利用能夠nginx將前端的指定路徑代理到後端的8080端口上。

conf/nginx.conf文件中增長location

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

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

相關文章
相關標籤/搜索