Home > other >  How to setup Angular routing on Tomcat?
How to setup Angular routing on Tomcat?

Time:11-09

I'm using Tomcat to host angular application with router. But when I try to use the routing I'm getting a 404 error (main/getting-started).

Tomcat is running on localhost:9443/main.

Router configuration:

 {path: 'getting-started', component: GettingStartedComponent},
 {path: '', component: codeComponent},
 {path: 'main', component: codeComponent}

Main works correctly. And getting-started works on ng serve.

Tried this solution, didn't work: https://medium.com/@nithin.biliya/deploying-angular-application-on-tomcat-server-fixing-deep-linking-issue-577565fe303d

Tried different baseHref in angular config and in index.html.

According to https://angular.io/guide/deployment,

Routed apps must fall back to index.html

If the application uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.

A routed application should support "deep links".

Now, how can I set it up on tomcat?

CodePudding user response:

For anyone else who had a problem with this issue. It is caused by

If the application uses the Angular router, you must configure the server to return the application's host page (index.html) when asked for a file that it does not have.

Solution that worked for me:

In your eclipse project with angular build that is served on Tomcat:

Inside META-INF folder edit a file context.xml and add RewriteValve:

 <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

If you don't have context.xml - create it and add the following xml:

<?xml version="1.0" encoding="utf-8"?>
<Context>
  <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
</Context>

Inside WEB-INF, create file rewrite.config (this file contain the rule for URL Rewriting and used by tomcat for URL rewriting). Inside rewrite.config, copy the below content:

RewriteCond %{SERVLET_PATH} !-f
RewriteRule ^/(.*)$ /index.html 

This will return the application's host page (index.html) when asked for a file that it does not have.

Now if the issue is not resolved - depending on your project settings you might need to change baseHref in angular.json or change the RewriteRule.

  • Related