北屋教程网

专注编程知识分享,从入门到精通的编程学习平台

vue3 + vite + TypeScript 编译打包部署后,刷新页面404

这个问题是 前端单页应用(SPA)在生产环境刷新时 404 的经典情况。
用 vite + vue3 + ts 打包部署后,前端路由是由 Vue Router 管理的,但生产环境的静态服务器(Nginx、Apache、Caddy 等)默认会直接去找对应路径的物理文件,如果没有就报 404。

解决办法:让服务器把所有路由请求交给 index.html
这样前端路由才能接管。


1. Nginx 部署

如果你用 Nginx,可以在配置里加:

server {
  listen 80;
  server_name yourdomain.com;

  root /var/www/yourapp/dist;

  index index.html;

  location / {
    try_files $uri /index.html;
  }
}

关键点就是 try_files $uri /index.html;,它会让 /xxx 这种前端路由都回退到 index.html。

2. Apache 部署

.htaccess 文件里加:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

3. Vite 配置基础路径

如果你部署在子目录(例如 https://your.com/app/),需要在 vite.config.ts 里设置:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: '/app/', // 如果你的部署路径是 /app/
})

4. Vue Router 模式

如果你用的是 createWebHistory 模式,就需要以上服务端回退。
如果不方便改服务器,可以用 createWebHashHistory,这样路由会是 /#/xxx,刷新不会 404,但 URL 不够美观。



推荐 生产环境改服务器配置 + 保持 createWebHistory,这样 URL 美观。

  • 如果不能改服务器,就用 createWebHashHistory。
  • 控制面板
    您好,欢迎到访网站!
      查看权限
    网站分类
    最新留言