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

VueJS项目打包dist部署后子页面刷新出现URL未找到404报错求助

解决Vue项目打包后刷新子页面404问题

这是单页应用(SPA)的典型问题:Vue使用前端路由,页面内跳转是通过JS动态修改浏览器URL,不会向服务器发送请求;但刷新页面时,浏览器会直接向服务器请求对应URL的物理资源,而服务器上并没有这个路径的文件,因此返回404错误。

以下是几种解决方式:

方式一:切换路由模式为hash

修改路由配置文件(通常是src/router/index.js),将mode从history改为hash:

const router = new VueRouter({
  mode: 'hash',
  routes: [
    // 你的路由配置
  ]
})

这种方式无需修改服务器配置,缺点是URL会带有#符号。

方式二:服务器端配置(适配history模式)

如果不想URL带#,需要在服务器上配置重写规则,将所有请求指向项目的index.html文件,由Vue前端路由处理。

Nginx配置

在Nginx的站点配置文件中,添加try_files指令:

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

配置完成后重启Nginx服务。

Apache配置

在服务器上的dist目录下创建.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>

确保Apache已经开启mod_rewrite模块。

IIS配置

在项目根目录创建web.config文件,添加重写规则:

<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>

注意事项

如果项目部署在服务器的子目录下(例如http://yourdomain.com/vue-app/),需要在vue.config.js中配置publicPath:

module.exports = {
  publicPath: '/vue-app/'
}

同时服务器配置中的重写路径也要对应调整(比如Nginx的try_files里的/index.html要改成/vue-app/index.html)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:32:20