Configure spring boot to redirect 404 to a single page app

Vovan picture Vovan · Jun 22, 2017 · Viewed 31.6k times · Source

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).

Answer

Jay Steven Hamilton picture Jay Steven Hamilton · Aug 6, 2018

This is the full Spring Boot 2.0 example:

@Configuration
public class WebApplicationConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/notFound").setViewName("forward:/index.html");
}


@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
    return container -> {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
                "/notFound"));
    };
  }

}