同事新开了一个项目vue2的脚手架,新写了一个项目打包后放服务器配置,为了方便就在同一个域名下开了一个test的后缀来访问,打包后发现访问不了。上传到正式服务器,因为是正式的二级域名没问题,通过尝试彼发现几个问题点以及解决办法
Vue项目
vue2
vue.config.js指定目录
module.exports = defineConfig({
publicPath: "/test",//指定项目目录
...
})
router/index.js
const router = new Router({
base: "test", //指定项目目录
mode: "history", // 去掉#,需要路由模式改为history
routes: routes,
});
vue3
vite.config.ts
export default defineConfig(({ command, mode }): UserConfig => {
const isBuild = command == 'build'
const root = process.cwd()
const env = parseEnv(loadEnv(mode, root))
return {
base: "/test/", // 关键代码,指定项目目录
// plugins: [vue(),],
plugins: setupPlugins(isBuild, env),
}
})
router/index.ts
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [...],
})
Uniapp
在根目录manifest.json找到web配置,运行的基础路径中加入目录名
服务端配置
配置nginx.conf 如果你在Nginx中配置了多个项目,每个项目使用不同的子目录,而在刷新页面后不能正常访问,可能是因为HTML5 History模式引起的问题。
当使用HTML5 History模式时,前端路由的URL(例如,/project/test)在刷新页面时可能会被解析为服务器上的路径,而不是在前端路由中。这可能导致Nginx服务器返回404,因为实际上没有对应的文件路径。
为了解决这个问题,你需要在Nginx配置中使用try_files来重定向请求到入口HTML文件
location /test {
alias /www/test/dist;
index index.html;
try_files $uri $uri/ /test/index.html; #指定
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]\.";
}
以下配置完成即可正常访问,刷新页面也可访问