-
前情提要:
涉及到多个服务部署在一个服务器,用一个nginx代理转发的情况,前端一直报http 405错误,后端服务也一直没有log,说明一直没有调用到后端。
查了网上关于nginx配置的文档,有针对root和alias的说明,有local 后面名称带不带“/”的说明,就是没有nginx配置的字段跟前后端哪些字段对应的说明。
我的nginx配置是门户统一配好的不能改,只能改代码找对应关系,自己动手丰衣足食。
-
开始折腾:
nginx固定内容,注意bef和bef_server两个前后端服务关联因子。
server {
listen 8080;
server_name localhost;
#compression-webpack-plugin压缩配置
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
#charset koi8-r;
#access_log logs/host.access.log main;
location /bef { #注意bef,http://localhost:8080/bef/是前端服务的baseusrl
alias D:\dists;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /bef_server { #注意bef_server,http://localhost:8002/bef_server/是向后端转发地址的baserurl
proxy_pass http://localhost:8002;
}
使用postman直发 http://localhost:8002/bef_server/login 正常执行,说明后端的yml配的访问根地址没有问题,是前端配置和nginx代理转发的问题。下记后端yml文件,port、context-path正确。
# Web服务配置
server:
# 端口配置
port: 8002 # hrp后端地址
servlet:
# 访问根路径
context-path: /bef_server #注意bef_server和nginx的proxy_pass的转发地址中有这个字段(location /bef_server代表bef_server会串在proxy_pass地址的后面)
session:
cookie:
# 防xss攻击(已被shiro托管)
http-only: true
nginx的bef_server对应axios.js中baseurl,需要修改。
let config = {
baseURL: "/bef_server", //注意bef_server
withCredentials: true, // Check cross-site Access-Control
};
对应开发环境代理,vue.config.js中publicpath的bef是前端访问地址根目录,proxy中是后端代理,是开发环境用,在产品环境,用nginx代替。
module.exports = {
publicPath:'/bef/', //注意前端访问地址变为localhost:8080/bef/
outputDir: 'dists',
assetsDir: "./static",
indexPath: './index.html',
lintOnSave: true,
transpileDependencies: [],
productionSourceMap: true,
devServer: {
port,
open: false,
overlay: {
warnings: false,
errors: true
},
// 配置代理
proxy: {
"/bef_server": {
target: 'http://localhost:8002/bef_server', //注意bef_server转发后端,开发环境用,nginx配置可以替代
changeOrigin: true, // 是否改变域名
ws: true,
timeout : 6000000,
pathRewrite: {
// 路径重写
"^/bef_server": ""
}
}
}
},
以上,通了。