You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地正常的/receipt路由部署服务器后报404 NotFound错误求助

部署后Vue路由/receipt出现404的排查方案

核心原因

本地正常但部署后404,绝大多数是Vue Router的history模式与服务器配置不匹配导致的。本地开发环境的dev-server会自动处理路由 fallback,但生产服务器不会默认做这件事——直接访问路由时,服务器会去查找对应物理文件,找不到就返回404。


排查步骤&解决方案

1. 确认路由模式

先检查你的路由初始化代码:如果用了createWebHistory()(history模式,URL不带#),必须配置服务器 fallback;如果是默认的createWebHashHistory()(hash模式,URL带#),一般不会出现这个问题。

示例history模式的路由配置:

import { createRouter, createWebHistory } from 'vue-router'
import PrintReceipt from '@/components/PrintReceipt.vue'

const router = createRouter({
  history: createWebHistory(), // 这里是关键
  routes: [
    {
      path: "/receipt",
      name: "receipt",
      component: PrintReceipt,
    }
  ]
})

2. 配置服务器Fallback规则

根据你使用的服务器,添加规则让所有路由请求都指向Vue的入口文件index.html:

  • Nginx:在站点配置中添加try_files规则
location / {
  try_files $uri $uri/ /index.html;
}

若项目部署在子路径(如/app/),修改为:

location /app/ {
  try_files $uri $uri/ /app/index.html;
}
  • 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>

子路径部署时,把RewriteBase /改成RewriteBase /app/

  • IIS:创建web.config文件,添加:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode" 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>
  </system.webServer>
</configuration>

3. 同步部署路径配置

如果项目不是部署在服务器根目录,需要同步配置路由的base参数和打包工具的公共路径:

  • 路由配置中设置base:
const router = createRouter({
  history: createWebHistory('/app/'), // 和部署路径保持一致
  routes: [...]
})
  • Vue-cli项目:在vue.config.js中设置publicPath:
module.exports = {
  publicPath: '/app/'
}
  • Vite项目:在vite.config.js中设置base:
export default defineConfig({
  base: '/app/'
})

4. 验证跳转逻辑

你的this.$router.resolve跳转逻辑本身没问题,但要额外确认:

  • 打包后PrintReceipt组件被正确打包,不存在路径错误
  • 服务器上的静态资源(js、css等)能正常访问,避免因资源加载失败导致路由无法初始化

内容的提问来源于stack exchange,提问作者Wanjala Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:33:31