Angular应用部署Apache Tomcat时路由与页面刷新问题咨询
解决方案:Tomcat部署Angular无哈希路由问题
核心原因
Tomcat会将Angular的前端路由URL当作真实的服务器资源路径去查找,找不到就返回404。但Angular是单页应用,所有路由请求都应该指向index.html,由前端路由系统处理。
步骤1:配置正确的base标签
根据Angular应用在Tomcat中的部署路径,修改index.html里的<base>标签:
- 若部署在
webapps/your-app目录(访问路径为http://域名/your-app/):
<base href="/your-app/">
- 若部署在Tomcat根目录(
webapps/ROOT):
<base href="/">
步骤2:配置Tomcat的URL重写规则
通过Tomcat的URL重写功能,将所有前端路由请求转发到index.html:
- 下载对应Tomcat版本的
tomcat-rewrite.jar,放入Tomcat的lib目录。 - 在Angular应用的
WEB-INF目录创建web.xml文件(无则新建),添加过滤器配置:
<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"> <filter> <filter-name>RewriteFilter</filter-name> <filter-class>org.apache.catalina.filters.RewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>RewriteFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> </web-app>
- 同样在
WEB-INF目录创建rewrite.config文件,添加重写规则:
# 排除静态资源,避免被错误重写 RewriteCond %{REQUEST_URI} !^.*\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ # 排除已存在的文件或目录 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 将符合条件的请求转发到index.html RewriteRule ^(.*)$ /your-app/index.html [L]
注:若部署在Tomcat根目录,把规则中的/your-app/index.html改为/index.html
步骤3:正确构建Angular应用
使用Angular CLI构建生产版本时,指定部署路径(非根目录时):
ng build --prod --base-href /your-app/
也可以在angular.json的projects -> 你的项目名 -> architect -> build -> options中设置baseHref为/your-app/,之后直接执行:
ng build --prod
验证
部署完成后,测试页面刷新、新窗口打开路由链接等操作,前端路由应正常工作,不再出现404错误。
内容的提问来源于stack exchange,提问作者SAI KAMIREDDY
相关产品推荐
相关产品推荐

