需求简介
前提,多个项目功能重复,每次开发都需要复制一份代码且需同时维护多个项目。如:后台管理功能中的菜单管理、角色管理等。
解决方案
1.抽离管理后台代码,单独打包成一个项目,利用nginx代理转发给对应的项目。如:
项目A地址为http://192.168.1.1:80 对应的管理后台地址为http://192.168.1.1:80/setting
项目B地址为http://192.168.1.1:81 对应的管理后台地址为http://192.168.1.1:81/setting
好处是解决同源策略,不用重新登录,同时又满足不同项目加载不同的管理后台、且只需要维护同一套代码。
2. 这里需要注意的是nginx在不同的serve需要代理到对应的服务器。如下
## 项目A对应的代理
server {
listen 80;
server_name www.aabb.com;
location / {
root /vueA/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /setting {
alias /setting/dist;
index index.html index.htm;
try_files $uri $uri/ /setting/index.html;
}
## 这里是后端服务A
location /api/ {
proxy_set_header Host $host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://192.168.2.1:8001;
}
}
## 项目B对应的代理
server {
listen 81;
server_name www.aabb.com;
location / {
root /vueB/dist
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /setting {
alias /setting/dist;
index index.html index.htm;
try_files $uri $uri/ /setting/index.html;
}
## 这里是后端服务B
location /api/ {
proxy_set_header Host $host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://192.168.2.2:8001;
}
}
- 这里要注意
alias /setting/dist;对应的是抽离出来的后端管理项目打包后的代码。 try_files $uri $uri/ /setting/index.html需要在前面加上/setting
3. 这里采用vue进行打包后台管理系统,需要配置,如下:
vue.config.js
module.exports = {
publicPath: '/setting', // 基本路径
}
router.js
const router = new VueRouter({
mode: 'history',
base: '/setting',
routes
})
- 上面的配置是把当前项目的基本路径改为/setting,与nginx代理保持一致。