I want to configure my Spring Boot app to redirect any 404 not found request to my single page app.
For example if I am calling localhost:8080/asdasd/asdasdasd/asdasd
which is does not exist, it should redirect to localhost:8080/notFound
.
The problem is that I have a single page react app and it runs in the root path localhost:8080/
. So spring should redirect to localhost:8080/notFound
and then forward to /
(to keep route).
This should do the trick: Add an error page for 404 that routes to
/notFound
, and forward that to your SPA (assuming the entry is on/index.html
):In case anyone stumbles here looking for how to handle Angular/React/other routes and paths in a Spring Boot app - but not always return index.html for any 404 - it can be done in a standard Spring controller RequestMapping. This can be done without adding view controllers and/or customizing the container error page.
The RequestMapping supports wild cards, so you can make it match against a set of well known paths (ie. angular routes etc.) in your application and only then return forward index.html:
Another option (borrowed from an old Spring article here: https://spring.io/blog/2015/05/13/modularizing-the-client-angular-js-and-spring-security-part-vii) is to use a naming convention:
The above configuration will match all paths that do not contain a period and are not already mapped to another controller.
Simply implementing the org.springframework.boot.web.servlet.error.ErrorController did the trick for me. I use SpringBoot 2.0 with React. (If you are interested in how to do that here is a boilerplate project made by me: https://github.com/archangel1991/react-with-spring)
I am not sure why is this working though.
Here the security configuration (SecurityConfig.java)
If not found any resource redirect to error page
Error page like
This is the full Spring Boot 2.0 example: