NextJS13 App Directory路由在Spring Boot中部署的404及API冲突问题
解决NextJS 13 App Directory静态资源在Spring Boot中的路由冲突问题
方案1:通过Spring MVC配置区分API与页面路由
先给所有后端API统一前缀(比如/api/),让Spring优先处理API请求,剩余非API路径自动匹配对应HTML文件:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.html"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/") .resourceChain(true) .addResolver(new PathResourceResolver() { @Override protected Resource getResource(String resourcePath, Resource location) throws IOException { Resource requestedResource = location.createRelative(resourcePath); // 非API路径且资源不存在时,尝试匹配对应HTML文件 if (!requestedResource.exists() && !resourcePath.startsWith("api/")) { return location.createRelative(resourcePath + ".html"); } return requestedResource.exists() ? requestedResource : null; } }); } }
- 优势:API请求正常匹配Controller,页面路由自动映射到对应HTML,不破坏NextJS客户端导航逻辑。
方案2:配置NextJS静态导出(适合纯静态应用)
如果你的应用不需要SSR/ISR等动态功能,修改next.config.js开启尾部斜杠:
/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', trailingSlash: true, } module.exports = nextConfig;
构建后每个路由会生成路由名/index.html结构,Spring访问/user/edit时会自动加载/user/edit/index.html,无需额外转发配置,天然避免路由冲突。
方案3:用Filter统一处理SPA路由
编写Filter拦截非API、非静态资源的请求,转发到对应HTML:
@Component public class SpaRoutingFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String path = req.getRequestURI(); // 排除API、静态资源(带后缀的文件)和根路径 if (!path.startsWith("/api/") && !path.contains(".") && !path.equals("/")) { request.getRequestDispatcher(path + ".html").forward(request, response); return; } chain.doFilter(request, response); } }
- 注意:如果有其他静态资源后缀(比如
.json),需要在判断条件里补充排除。
内容的提问来源于stack exchange,提问作者Man Man Yu
相关产品推荐
相关产品推荐

