问题场景(hash模式,目前只研究了hash)
- 想一个nginx部署多个文件目录
- 想增加后缀(比如:app端和web端同时配置在nginx中根据后缀不同走不同的文件路径)
- 登录成功刷新或者退出登录不是404就是跳转错误
- 本地和服务器区分,本地不加后缀,服务器加后缀,每次发布都要改配置,怎么样一次改动,两种场景都自动生效
- 刷新报错,样式问题,各种404等等
hash配置完后登录或者退出要么跳不过去,要么404,问题解决过程
还有有一种更好的、快捷的方式,就是将后缀配置的环境变量中,如下
// 配置在环境env中: VUE_APP_PATH = '/manage/'
publicPath: process.env.VUE_APP_PATH,
// publicPath : process.env.NODE_ENV === 'production' ? './' : '/',
还是下面改动的方式,只是不需要应用全局变量文件了,只需要在改动的地方加process.env.VUE_APP_PATH
举个例子login.vue就可以这样改(减少了引用和判断这一操作)
this.$router.push({ path: this.redirect || process.env.VUE_APP_PATH }).catch(()=>{});
1. 全局(settings.js[src目录下])配置文件增加
publicPath: '/manage/'
2. 修改退出登录或者登录时的返回路径(目前改了四处Navbar.vue、request.js、login.vue、vue.config.js)
Navbar.vue
// 引入配置
const defaultSettings = require('../../settings.js')
// 将原来 location.href = '/' 替换
location.href = (process.env.NODE_ENV === 'production' ? defaultSettings.publicPath : '/');
request.js 与上面的步骤一样
const defaultSettings = require('../settings.js')
location.href = (process.env.NODE_ENV === 'production' ? defaultSettings.publicPath : '/');
login.vue 与上面有一点不一样注意:(location.href = this.redirect || “/”;)替换
const defaultSettings = require('../settings.js')
// 替换为如下
this.$router.push({ path: this.redirect || (process.env.NODE_ENV === 'production' ? defaultSettings.publicPath : '/' ) }).catch(()=>{});
vue.config.js
const defaultSettings = require('./src/settings.js')
// 增加
publicPath: process.env.NODE_ENV === "production" ? defaultSettings.publicPath : "/",
3. nginx配置
location /gather {
proxy_pass http://127.0.0.1:8087/gather;
index index.html index.htm index.jsp;
}
location /prod-api/ {
proxy_pass http://127.0.0.1:8087/gather/;
}
location /manage/ {
alias d:/gather/java/gatherManage/;
try_files $uri $uri/ /index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
4 文件目录
5.效果
1. 本地
2 服务器
知识点补充
反向代理实例说明:
如果 proxy_pass 后缀加了/,最后访问时,会去除匹配字符 /prod-api/
# 没测试
location /prod-api {
proxy_pass http://127.0.0.1:8087/;
}
# 已测
location /prod-api/ {
proxy_pass http://127.0.0.1:8087/;
}
http://test.com/prod-api/test 会被转化为 http://127.0.0.1:8087/test
如果没有加/,就不会去除/prod-api/
# 已测
location /prod-api/ {
proxy_pass http://127.0.0.1:8087;
}
location /prod-api {
proxy_pass http://127.0.0.1:8087;
}
http://test.com/prod-api/test 会被转化为 http://127.0.0.1:8087/test/prod-api/test
2. 正向代理
如果 location配置的加了/就是目录不加就是固定文件
location /test/login.png {
root d:/gather/java/gatherManage/;
index index.html;
try_files $uri $uri/ /index.html last;
}
访问 /test/login.png 会被代理成 d:/gather/java/gatherManage/test/login.png
location /test/ {
root d:/gather/java/gatherManage/;
index index.html;
try_files $uri $uri/ /index.html last;
}
此时就是访问 /test/目录下
如果使用alias,不使用root也有一点区别,匹配字符会被替换
location /manage/ {
alias d:/gather/java/gatherManage/;
try_files $uri $uri/ /index.html;
}
/manage/test.js 会被代理为 d:/gather/java/gatherManage/test.js