I am serving an SPA made with create-react-app and react-router using Spring Boot 2.1.0 with this configuration
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/**/{path:[^\\.]+}")
.setViewName("forward:/");
}
}
Basically what it does is always serve index.html unless there's a period in the path. I would like to align this with create-react-app's provided .htaccess
. How can I make Spring Boot match this functionality?
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
To reroute "404 : file not found" to "forward:/", which I think is what the .htaccess does, change your WebMvcConfiguration to...
@Configuration
public class WebMvcConfiguration implements ErrorViewResolver
{
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
if (status == HttpStatus.NOT_FOUND) {
return new ModelAndView("forward:/");
}
return null;
}
}
You can catch-all unhandled view controller like below when no other route has been found.
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.setOrder(Ordered.LOWEST_PRECEDENCE);
registry.addViewController("/**").setViewName("forward:/index.html");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With