Spring Boot托管NextJS静态导出文件时,能否显示NextJS的404页面?
解决Spring Boot整合NextJS时404页面显示问题
问题分析
你的场景是Spring Boot作为后端容器,NextJS构建产物放在resources/static目录下,但访问不存在的路径时,Spring默认的白标错误页面会覆盖Next生成的404.html。核心原因是Spring Boot的错误处理机制会接管所有未匹配的请求,而非直接返回静态资源中的404页面。
解决方案
1. 确保NextJS构建产物包含404.html并正确复制
首先确认你的NextJS项目在静态导出模式下构建时生成了404.html,同时检查maven-resources-plugin配置,确保将Next构建目录(通常是src/main/react/out)下的所有文件完整复制到resources/static:
<plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> <executions> <execution> <id>copy-react-build</id> <phase>process-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.outputDirectory}/static</outputDirectory> <resources> <resource> <directory>src/main/react/out</directory> <filtering>false</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin>
2. 自定义ErrorController转发到Next的404.html
创建一个自定义错误控制器,让Spring Boot在捕获到未匹配路径的错误时,转发到静态资源中的404.html,这样就能复用Next生成的带样式的404页面:
import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class CustomErrorController implements ErrorController { @RequestMapping("/error") public String handleError() { // 转发到NextJS生成的404静态页面 return "forward:/404.html"; } }
3. 验证效果
启动Spring Boot应用,访问任意不存在的路径,此时应该显示NextJS生成的404.html页面,且页面样式与开发环境完全一致(因为页面引用的CSS/JS资源都是静态目录下的正确路径)。
额外说明
如果你的NextJS使用了客户端路由或动态路由,还需要配置Spring Boot将所有未匹配的路径转发到index.html以支持客户端路由跳转,但针对404场景,上述配置已足够解决问题。
内容的提问来源于stack exchange,提问作者Ben Chilcott
相关产品推荐
相关产品推荐

