Reputation: 315
I'll tell you what happens by following steps:
1) I have my app project based on Angular 4.0.2. I'm using routing. These are my routes in app.module.ts:
const routes: Routes =
[
{ path: '', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'login', component: LoginComponent }
];
So the first screen of the web application is Login.
2) I executed the command ng build -prod
3) I move the folder dist into Tomcat webapps folder
4) I modified the file index.html changing base href. Now it's
5) In /Tomcat9/conf/context.xml, I added the following instruction:
<Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
6) I created the folder WEB-INF, then I created the file rewrite.config, this file contains: # If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
7) I started Tomcat server
8) Next I openned a Mozilla browser and I put in address bar localhost:8080/dist/ It appears the login screen with 2 textboxes (user and pass) and one button for login.
9)When I press the button with user and pass valid. it goes to dashboard screen and I see the address bar changes to: localhost:8080/dist/dashboard.
10) After that, I go to address bar and I wrote manually: localhost:8080/dist/dashboard.
Then I press Enter and it appears Error 404.
It should keep showing dashboard screen and not Error 404.
This app works well in Apache server with .htaccess, but not in Tomcat 9
Why is not showing dashboard screen in this case if I configured the rewrite.config? what is missing in order to avoid error 404?
Upvotes: 0
Views: 1309
Reputation: 31
Thanks to the above solutions, with angular 11 and tomcat 9, just now (2021), I've tried them, but with no results. Then I came to a different approach, all in the war with angular app.
In web.xml
<error-page>
<error-code>404</error-code>
<location>/r404</location>
</error-page>
in the java source:
@WebServlet(urlPatterns = {"/r404/*"})
public class R404Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect(request.getContextPath());
}
}
Upvotes: 1
Reputation: 3454
It seems that the rewrite rules are not working. Try these rules:
#Check if the uri ends with an file extension
RewriteCond %{REQUEST_URI} .*\.(.*)$ [OR]
#Check if the uri contains /api/
RewriteCond %{REQUEST_URI} ^(.*)(/api/).*$ [OR]
RewriteRule ^(.*)$ - [L]
#If the requested resource doesn't exist, use index.html
RewriteRule ^(.*)$ /index.html
Upvotes: 2