react routing is able to handle different url path but tomcat returns 404 not available resources

First, you must be aware of the following differences when using react-router.

When you enter localhost:3003/test/ in your browser, it will request the server, and then it will receive /test/index.html, the js bundle, css, …

After that, whenever you click an internal link (eg. localhost:3003/test/t/), your browser will not request the server again. React-router will resolve this client-side, re-render portions of the page, and update browser’s address bar (using HTML5 pushstate()), without triggering another server request.

When you enter localhost:3003/test/t/ directly in the address bar, your browser will request the server, and Tomcat does not have /test/t/index.html or so, and it returns a 404. It’s because Tomcat doesn’t know anything about react-redux nor javascript.

A way to handle this is to configure 404 errors to be forward to /test/index.html. It’s probably how your webpack dev server is configured by default.

There is plenty of examples of doing this on apache, if you have one in front of our Tomcat.
Search for html5 pushstate apache config.

Here is an example:

httpd.conf:

...
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>
...

If you are using Tomcat alone, you may try to specify this in the web.xml, inside your .war file:

...
<error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
</error-page>
...

Note that this is not a react-router specific problem, every app that uses HTML5 pushstate() needs to handle this somehow. Javascript servers may handle this more seamlessly though.

Leave a Comment