Nginx端口轉發的命令是proxy_pass,官方介紹參考這裏。咱們在location上下文中配置轉發,可是要注意,轉發的目標路徑是關鍵。有的人說是跟結尾的斜槓有關係,其實沒有那麼複雜,看看官方解釋:vue
If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directivenode
If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:nginx
什麼叫 With a URI 呢?實際上這裏的理解應該是不包含協議、域名和端口的,好比http://localhost:3000/node就是,由於它攜帶一個/node。web
先來看這個配置,without a URI的狀況vue-router
location /node/ {
proxy_pass http://localhost:3000;
}
複製代碼
以http://web.17lvju.com/node/node
爲例,代理後,Nginx真正訪問的會是會在把匹配路徑原封不動地加在localhost:3000後面。 依舊是http://localhost:3000/node/node
express
再看,With a URI的狀況api
location /node/ {
proxy_pass http://localhost:3000/; #這裏結尾加了一個斜槓
}
複製代碼
加了一個斜槓,變成With a URI,則proxy_pass配置的URI會取代location中匹配的路徑,也就是本例中/會替換/node/。 以http://web.17lvju.com/node/node
爲例,代理後,Nginx真正訪問的會是http://localhost:3000/node
bash
因此應該採用第二種,也就是with a uri的模式,讓nginx對路徑作一次剝離+轉發app
採用http-proxy-middleware
模塊
const express = require("express");
const proxy = require('http-proxy-middleware');
const os = require('os');
const app = express();
const HOST = 80;
var options = {
target: 'http://localhost', // 目標主機
router: {
'/admin/ipfs': 'http://localhost:4422',//若是請求路徑是/api/rest,則將url的請求路由重定向
},
pathRewrite: {
'^/admin/ipfs': '/'
}
};
var exampleProxy = proxy(options); //開啓代理功能,並加載配置
app.use('/', exampleProxy);//對地址爲’/‘的請求所有轉發
let ip_reg= /\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}/;
let ip_arr= JSON.stringify(os.networkInterfaces()).match(ip_reg);
app.listen(HOST, function(){
console.log("running on ------> "+ ip_arr[0]+ ":"+ HOST);
});
複製代碼
一樣的,options中的router
配置負責轉發,而pathRewrite
負責剝離 若是沒有剝離這一步,能夠進入index.html,可是頁面中加載的靜態文件全都會加載失敗,由於靜態文件訪問的路徑是 未剝離的路徑+/static/...
剝離的意義:由於咱們是要以單端口接收訪問,轉發給多端口,不剝離,則接收什麼轉發什麼,剝離,則將接收的剝離之後再轉發
vue中須要配置vue-router初始化時候的參數base
,這個base
指定了vue-router對url識別的起始區域在base
以後
//src-router-index.js
const router = new Router({
routes,
base: '/app/17mall/',
mode: 'history'
})
複製代碼
配置assetsPublicPath
參數,這個參數會加到靜態資源請求路徑的前邊