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
参数,这个参数会加到静态资源请求路径的前边