Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat 8 URL Rewrite

I have an AngularJS webapp and Jersey backend. I need to setup URL rewriting, so everything except given exceptions will be rewritten to Angular's index.html.

Eg.:

http://my.domain.com/about will be rewritten
http://my.domain.com/photos/photo1.jpg will NOT be rewritten (file photo 1 exists)
http://my.domain.com/rest/myservice will be NOT be rewritten (it is a call to REST service)

I have set up the Tomcat 8 URL Rewrite Valve as follows:

in conf/server.xml

<Host name="my.domain.com" appBase="webapps/MyDomainServer" unpackWARs="true"
           autoDeploy="true"
           xmlValidation="false" xmlNamespaceAware="false">
  <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />
  <!-- access logging, aliases,...-->
</Host>

in conf/Catalina/my.domain.com/rewrite.config

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} ^/rest.*
RewriteRule ^ - [L]

RewriteRule ^ index.html [L]

Tomcat ignores my rewrite settings, nothing is rewritten, no error/exception is in the log. What am I doing wrong? Thanks in advance.

I have tried to move RewriteValve to config.xml in META-INF and rewrite config to WEB-INF, but it behaved in the same way.

like image 884
kamelot Avatar asked Feb 27 '15 14:02

kamelot


People also ask

What is rewrite valve in Tomcat?

The rewrite valve can be configured as a valve added in a Host. See virtual-server documentation for informations how to configure it. It will use a rewrite. config file containing the rewrite directives, it must be placed in the Host configuration folder. It can also be in the context.xml of a webapp.

What is URL rewrite in Apache?

URL rewriting purpose is to change the appearance of the URL to a more user-friendly URL. This modification is called URL rewriting. For example, http://example.com/form.html can be rewritten as http://example.com/form using URL rewriting.


2 Answers

I have found the solution, problem was in wrong/faulty rewrite.config file. Correct should be:

RewriteCond %{REQUEST_URI} ^/(css|img|js|partials|rest|favicon).*$
RewriteRule ^.*$ - [L]

RewriteRule ^.*$ /index.html [L,QSA]

On the first line are enumerated URIs which should not be rewritten. Everything else will be rewritten to index.html.

like image 143
kamelot Avatar answered Sep 23 '22 05:09

kamelot


Is this deployed as a java web app (WAR)? You could implement this in your web.xml:

<servlet>
   <servlet-name>index</servlet-name>
   <jsp-file>/index.html</jsp-file>
</servlet>

<servlet-mapping>
   <servlet-name>index</servlet-name>
   <url-pattern>/</url-pattern>
   <url-pattern>/about</url-pattern>
   .. as many as you need ..
<servlet-mapping>
like image 45
Nicholas Hirras Avatar answered Sep 22 '22 05:09

Nicholas Hirras