Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat Rewrite Rules Angular 5 Application?

I have developed an application containing Routing in Angular 5 and I have built it with ng build --base-href /myApp/ --prod. Now I want to deploy it on a tomcat server running local on my Laptop.

The Problem is, that whenever i reload a page of my application in the browser, I get the error:

404 The requested resource is not available

I have searched in the internet for solving strategies, but nothing that I have found helped me. I am pretty sure that I have to declare some Rewrite rules but I have no Idea how they should look like and where I have to declare them.

Somebody who have an idea how to solve this issue? Thanks in advance.

like image 945
jRyze Avatar asked Nov 22 '25 21:11

jRyze


2 Answers

The application deep links will not work without the redirect rule on the server. All the deep links have to redirect to the application index.html by the server.

To setup the tomcat to redirect any deep links -

  1. Configure the RewriteValve in server.xml
  2. Write the rewrite rule in rewrite.config

1. Configure the RewriteValve in server.xml

Edit the ~/conf/server.xml to add the below Valve inside the Host section as below –

...
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

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

...
      </Host>
...

2. Write the rewrite rule in rewrite.config

Create directory structure – ~/conf/Catalina/localhost/ and create the rewrite.config file inside it with the below content. Note - here I am considering /myApp as the context path of the application.

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

After setting this up restart the tomcat server and you can hit the deep links of the application which will route to the correct components inside the angular application.

You can refer to this post for more details.

like image 194
Nithin Kumar Biliya Avatar answered Nov 25 '25 11:11

Nithin Kumar Biliya


Maybe you need a web.xml entry in the WEB-INF directory to redirect all unknown URLs to your default index.html

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>My Angular Application</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <error-page>
        <error-code>404</error-code>
        <location>/index.html</location>
    </error-page>
    <error-page>
        <error-code>410</error-code>
        <location>/index.html</location>
    </error-page>
</web-app>
like image 22
bjb Avatar answered Nov 25 '25 10:11

bjb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!