項目環境:
以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 # 從新讀取配置文件
對於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
有時一個Nginx中放了好幾個子項目,須要將不一樣的項目經過不一樣的路徑來訪問。npm
對於項目1而言,修改vue.config.js
文件的publicPath
:json
publicPath: '/vue1/'
對於項目2而言,修改vue.config.js
文件的publicPath
:windows
publicPath: '/vue2/'
分別在vue項目根目錄中使用命令npm run build
建立輸出文件,將dist文件夾下的全部內容複製到nginx目錄下的webapp/vue1
和webapp/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/vue1
、http://localhost/vue2
訪問項目一、項目2。
當先後端項目分別部署在同一臺機器上時,因爲沒法使用相同的端口,故後端通常會將端口號設置成不一樣的值(例如8080),可是當前端向後端請求資源時還要加上端口號,未免顯得麻煩,故利用能夠nginx將前端的指定路徑代理到後端的8080端口上。
在conf/nginx.conf
文件中增長location
:
location /api { proxy_pass http://localhost:8080/api; }
這樣,當前端訪問/api
路徑時,實際上訪問的是http://localhost:8080/api
路徑。