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

Vue.js应用部署Tomcat后刷新404的Tomcat配置方案咨询

解决Vue SPA在Tomcat下刷新404的配置方案

你的场景是Vue单页应用部署在Tomcat的webapps/front目录,后端Spring应用在ROOT目录,刷新时因Tomcat无法匹配前端路由路径导致404,以下是两种可行的配置方案:

方案一:前端应用独立配置错误页转发(推荐)

该方案仅作用于front应用,不会影响后端服务,步骤如下:

  1. 在webapps/front/WEB-INF目录下创建(若不存在)web.xml文件
  2. 添加404错误页转发规则,让Tomcat将所有未匹配到资源的请求转发到Vue入口index.html:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <error-page>
        <error-code>404</error-code>
        <location>/index.html</location>
    </error-page>
</web-app>

方案二:使用Tomcat RewriteValve实现精准路由转发(适合复杂场景)

需Tomcat 7.0.42及以上版本,可精准过滤静态资源和API路径:

  1. 编辑Tomcat根目录下的conf/server.xml,在目标Host节点内添加RewriteValve:
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
    <!-- 保留原有配置 -->
    <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
</Host>
  1. 在conf/Catalina/localhost目录下新建front.xml,配置针对front应用的Rewrite规则:
<Context docBase="front" path="/front">
    <Rewrite>
        <Rule>
            <!-- 排除静态资源请求,避免转发 -->
            <Condition test="%{REQUEST_FILENAME}" pattern="\.(js|css|png|jpg|gif|ico|svg|woff2)$" negate="true" />
            <!-- 若前端有调用后端API的路径,可在此排除(示例为/front/api/,根据实际调整) -->
            <Condition test="%{REQUEST_URI}" pattern="^/front/api/" negate="true" />
            <!-- 将符合条件的请求转发到index.html -->
            <Rule pattern="^/front/(.*)$" substitution="/front/index.html" />
        </Rule>
    </Rewrite>
</Context>

关键前置配置

确保Vue项目打包时设置正确的publicPath,避免路由路径错误:
在项目根目录的vue.config.js中添加:

module.exports = {
  publicPath: '/front/'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:00:11