如何配置nginx支持多级目录vue项目history模式?
摘要:本文详细说明了nginx部署vue项目配置细节,介绍了如何在nginx有上下文时,配置二级目录,甚至是多级路径后,vue项目的history模式也能正常使用。方便在项目开发后配合部署人员build要发布的项目。因为使用的项目使用的是cli
介绍
本文是篇详细的介绍vue项目在history模式下发布时build,项目如何配置,nginx如何配置,才能正常的使用历史模式。或者在二级目录下,多级路径下也能正常使用历史模式。
本文的例子中假设,nginx全部都是配置在 flytree.can 域名下。
且路由中配置有以下路径:
const routes = [
{ path: '/', redirect: "/index"},
{ path: '/login', component: Login },
{ path: '/welcome', component: Welcome }
]
vite下配置
以下为vue3, vue-router4.x 基于vite构建下的配置
二级路径
url
对应打开路由
http://www.flytree.can/web/login
/login
http://www.flytree.can/web/welcom
/welcom
vue-router 中要配置base
createWebHistory() 中有可选参数 base 支持配置:// router.js
const router = createRouter({
history: createWebHistory("/web/"),
routes: constantRoutes,
});
vite 构建增配置 base// vite.config.js
export default defineConfig(({ mode, command }) => {
return {
base:'/web/',
}
...
})
nginx 配置location /web {
alias /home/foo/workspace/xpos/web/;
try_files $uri $uri/ /web/index.html;
}
webpack下配置
以下为vue2, vue-router3.x 基于 webpack 下的配置,更新于2021-07-17 02:01
一级路径的配置
应用放在服务器根目录下。路由也就是域名后的第一级路径。如:
url
对应打开路由
http://www.flytree.can/login
/login
http://www.flytree.can/welcom
/welcom
路由配置
const router = new VueRouter({
mode: 'history',
routes
})
nginx配置
location / {
try_files $uri $uri/ /index.html;
}
二级路径的配置
应用不是放在服务器根目录下,而是location有上下文的。如配置了web上下文,则:
url
对应打开路由
http://www.flytree.can/web/login
/login
http://www.flytree.can/web/welcom
/welcom
路由配置
如果在ngnix代理的时候不是配置到根路径/的话,则要配置base,它指定的是应用的基路径。例如,如果整个单页应用服务在 /app/ 下,然后 base 就应该设为 "/app/"。
router/index.js配置:
const vueRouter = new Router({
mode: "history",
base: "/web",
routes: routes
})
配置了base后,应用就会在base之后打开了,如,后面配置了个/login路由,则是在/web/login中打开此路由。
项目config配置
注:由于项目里使用的是老版本的vue-cli,新版本@vue/cli配置会在旁说明。
老版本的配置文件在config/index.js中,如果是cli 3.x后续版本,需在项目 (和 package.json 同级的) 根目录中创建vue.config.js文件进行配置。
const path = require('path');
module.exports = {
module.exports = {
build: {
// 指定生成的 index.html 的输出路径 (相对于 配置文件所在路径)。也可以是一个绝对路径。
