如何为内嵌Tomcat的Jhipster+Angular Jar应用配置重写规则
解决Jhipster+Angular单Jar部署时路由重定向问题
方案一:使用Spring MVC控制器转发(推荐)
无需配置Tomcat RewriteValve,直接通过Spring MVC拦截非API、非静态资源的请求,转发到index.html:
@Controller public class SpaForwardController { // 匹配所有不包含api/css/js/assets等前缀的路径 @GetMapping(value = "/{path:(?!api|css|js|assets|favicon.ico|robots.txt).*}") public String forwardToIndex() { return "forward:/index.html"; } }
这个方式依赖Spring MVC的路径匹配,不会和Jhipster的现有配置冲突,也无需额外Tomcat阀门配置。
方案二:修复Tomcat RewriteValve配置
如果坚持使用RewriteValve,按以下步骤调整:
1. 修正WebConfigurer中的Valve配置
确保正确指定rewrite.config的路径,Jar包中需将配置文件放在src/main/resources/META-INF/resources目录下,然后配置:
@Bean public TomcatServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); RewriteValve rewriteValve = new RewriteValve(); // 指定Jar内的规则文件路径 rewriteValve.setConfPath("META-INF/resources/rewrite.config"); tomcat.addEngineValves(rewriteValve); return tomcat; }
2. 调整rewrite.config规则顺序
规则按先排除、后重写的顺序编写,确保API和静态资源不被拦截:
# 排除API接口路径 RewriteCond %{REQUEST_URI} ^/api/.*$ RewriteRule ^ - [L] # 排除静态资源文件 RewriteCond %{REQUEST_URI} ^/(css|js|assets|favicon.ico|robots.txt).*$ RewriteRule ^ - [L] # 仅当请求的文件/目录不存在时才重写(避免覆盖真实静态资源) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 重写所有其他请求到index.html RewriteRule ^ /index.html [L]
3. 检查Spring Security配置
确保Angular路由路径(如/login)不被Spring Security拦截,在SecurityConfiguration的configure(WebSecurity web)方法中添加忽略规则:
@Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/login", "/signup", "/dashboard") // 添加所有Angular路由路径 .antMatchers("/css/**", "/js/**", "/assets/**", "/favicon.ico", "/robots.txt"); }
通用检查项
- 确认Angular打包后的
dist目录内容已正确复制到Spring Boot项目的src/main/resources/static目录,可通过Maven插件自动完成:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-angular-dist</id> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.outputDirectory}/static</outputDirectory> <resources> <resource> <directory>${project.basedir}/frontend/dist</directory> <filtering>false</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin>
- 查看RewriteValve日志,确认
/login请求是否匹配到重写规则,若未匹配,检查规则中的路径正则是否覆盖目标路由。
内容的提问来源于stack exchange,提问作者Martin Zeller
相关产品推荐
相关产品推荐

