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

如何在Tomcat上配置Angular路由?解决404跳转异常

解决Tomcat部署Angular路由应用的404问题

一、确认Angular构建配置

因为你的应用部署在Tomcat的/main上下文路径下,构建时必须指定匹配的baseHref和deployUrl:

  • 命令行构建(临时生效):
ng build --base-href /main/ --deploy-url /main/
  • 或在angular.json中配置(永久生效):
    找到projects -> 你的项目名 -> architect -> build -> options,添加:
"baseHref": "/main/",
"deployUrl": "/main/"

构建完成后,将dist目录下的所有文件拷贝到Tomcat的webapps/main目录中。

二、配置Tomcat URL重写规则

Tomcat默认无法识别Angular的前端路由,需要配置重写规则,把所有路由请求转发到index.html,让Angular接管路由逻辑:

方法1:使用RewriteValve(推荐,灵活无副作用)

  1. 打开Tomcat安装目录下的conf/server.xml,找到<Host>标签,添加重写阀配置:
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
  1. 在你的应用目录webapps/main/WEB-INF下创建rewrite.config文件,写入规则:
# 排除静态资源请求,避免重写assets、样式、图标等路径
RewriteCond %{REQUEST_URI} !^/(main/)?(assets|scripts|styles|favicon\.ico).*$
# 将所有/main/开头的非静态资源请求转发到index.html
RewriteRule ^/main/(.*)$ /main/index.html [L]

方法2:使用404错误页跳转(简单但有局限)

如果不想配置重写阀,可在webapps/main/WEB-INF/web.xml中添加404错误页配置:

<error-page>
    <error-code>404</error-code>
    <location>/main/index.html</location>
</error-page>

这种方式是当Tomcat返回404时跳转到index.html,Angular会接管路由,但可能会掩盖真正的资源不存在问题。

三、清理冗余路由配置

你的路由中path: 'main'会生成/main/main路径,和Tomcat的上下文路径冲突,建议删除这条路由,避免混淆:

{path: 'getting-started', component: GettingStartedComponent},
{path: '', component: codeComponent}

完成以上配置后,重启Tomcat,访问localhost:9443/main/getting-started即可正常加载路由页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:05:30