如何通过NGINX将Vue3 Vite应用部署在指定路径/auth下
解决Vue3/Vite部署在NGINX子路径
/auth下的资源路径问题 这个问题的核心是Vite和Vue应用默认以根路径/生成资源链接,不知道自己部署在子路径下,再配合NGINX配置的细节调整就能解决,具体步骤如下:
1. 配置Vite的基础路径
在项目的vite.config.js(或vite.config.ts)中指定base选项为子路径/auth/,这样Vite生成的所有资源(包括@vite/client、静态文件、组件样式等)都会自动带上该前缀:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], base: '/auth/' // 末尾必须带斜杠,确保路径拼接正确 })
2. 配置Vue Router的基础路径(若使用路由)
如果项目用到了Vue Router,需要同步设置路由的base属性,避免路由跳转时脱离子路径:
import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' const router = createRouter({ history: createWebHistory('/auth/'), // 传入子路径作为路由基础 routes: [ { path: '/', component: Home } // 其他路由规则... ] }) export default router
3. 优化NGINX配置
原配置的rewrite可以简化,通过调整proxy_pass的写法实现更可靠的路径转发:
location /auth/ { proxy_pass http://127.0.0.1:5143/; // 注意末尾的斜杠,会自动把/auth/后的路径拼接到代理地址后 proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
末尾的斜杠是关键:NGINX会将/auth/xxx直接转发到http://127.0.0.1:5143/xxx,无需额外的rewrite规则。
验证操作
- 执行
sudo nginx -s reload重启NGINX使配置生效 - 重启Vite开发服务(开发环境)或重新打包部署(生产环境)
- 访问
example.com/auth,检查浏览器网络请求,所有资源路径都应带有/auth/前缀
内容的提问来源于stack exchange,提问作者v-kessler
相关产品推荐
相关产品推荐

