Vue 3 + Vue Router 4静态网站非根路由刷新报错求助
问题解决:Vue Router 刷新非根路由出现404
核心原因
你使用了createWebHistory(HTML5 History模式),这种模式下前端路由由客户端处理,但刷新页面时,浏览器会直接向服务器请求当前路径(比如/classroom),而服务器上并没有对应路径的物理文件,因此返回404错误。根路由正常是因为服务器默认会返回index.html。
解决方案
1. VSCode Live Server 运行生产构建文件
在项目根目录创建.vscode/settings.json,添加以下配置,让Live Server把所有请求都 fallback 到index.html:
{ "liveServer.settings.root": "/dist", "liveServer.settings.mount": [ ["/", "./dist/index.html"] ] }
重启Live Server即可生效。
2. IIS 服务器配置
需要通过URL重写规则,把所有非静态资源的请求转发到index.html:
- 确保IIS已安装URL重写模块(可通过IIS管理器的Web平台安装程序添加)。
- 在项目部署目录创建
web.config文件,写入以下内容:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Vue Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="/index.html" /> </rule> </rules> </rewrite> <staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> </staticContent> </system.webServer> </configuration>
如果项目部署在IIS的子目录(比如/vulcan),需要把<action>里的url="/index.html"改成url="/vulcan/index.html",同时在vite.config.js中配置正确的base路径:
// vite.config.js export default defineConfig({ base: '/vulcan/', // ...其他配置 })
3. 额外检查点
- 确认
import.meta.env.BASE_URL的值正确,生产环境下该值由vite.config.js的base选项决定。 - 你的路由配置和
RouterLink使用name跳转的方式是正确的,无需修改。
内容的提问来源于stack exchange,提问作者Energetic Pixels
相关产品推荐
相关产品推荐

