I am new in reactjs
and I have a little project in reactjs
to play with and learn it. I need to have to type of headers which will be shown based o
Tomcat 8 and above has a simple built-in solution for this. You do not need to put it behind Apache to handle this, or switch to hash routing, or hack a redirect page to go back to a different place on your own server...
Use Tomcat Rewrite
It works for any single-page-app framework that has UI-routing like React, Angular, ExtJS, etc.
In a nutshell:
1) Add a RewriteValve to
/tomcat/webapps/{your-web-app-directory}/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
... your other context items
</Context>
2) Create a file named: /tomcat/webapps/{your-web-app-directory}/WEB-INF/rewrite.config
and then add rewrite rules for any paths you want to point to your index page:
RewriteRule ^/user(.*)$ /index.html [L]
RewriteRule ^/home(.*)$ /index.html [L]
RewriteRule ^/contact(.*)$ /index.html [L]
These rules tell Tomcat to send all requests with these three named paths straight to index.html.
3) Restart Tomcat
The rules can get fancier, like sending all requests to index.html except for a certain path, which is useful for /api
calls that have to go somewhere besides index.html
. The link above covers additional examples of how to use Tomcat Rewrite.
My solution is like a workaround for JSP engines (e.g. Tomcat), but it works great with minimal code.
I created an "index.jsp" parallel to "index.html" (in the content root folder) with following code:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="index.html"%>
I configured all urls to redirect to this JSP in web.xml
web.xml
<servlet>
<servlet-name>index</servlet-name>
<jsp-file>index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>index</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Now any URL requested to Tomcat will internally get redirected to index.jsp that is effectively index.html. Once react-router loads in browser, it takes care of rendering the right component and subsequent requests.