How to specify web application-specific custom URL rewrites when using Tomcat server?

Recently, I had been working on a UI project where we used Ember.js as the MVC framework to render screens for the single-page application we were building.

One of the advantages that MVC frameworks like Ember.js and Angular.js provide us is the support for HTML5 pushState functionality using the history feature. This history feature allows the user to navigate back to previous screens of the single-page application easily. 

But the downside is that they append the route information to the end of the application-context, thereby creating new URLs that cannot be individually bookmarked. For example, if I had a route /Screen1 as a route that takes me to the Screen1 of my application, these frameworks automatically navigate to a URL like http://localhost:8080/<APP>/Screen1, where <APP> is my application-context. As we can see, this URL in itself cannot be bookmarked as Tomcat as no idea of this URL in isolation. This can lead to unforeseen errors that the user is not going to like. The requirement is that whenever URLs of the form http://localhost:8080/<APP>/* is hit, except for static content, all other relative URLs has to be served by the application and not try to be resolved by Tomcat server. How do we achieve this?

One way to achieve this is using Apache HTTP server and configuring URL re-writes. But what if you do not have Apache HTTP server already installed or do not want to introduce one into your eco-system just for this requirement? UrlRewriteFilter comes to the rescue.

I am not delving into the usages of this particular library and the filter as such, which we can find in abundance in the aforementioned website, but capturing a few points I noted when trying to figure out the right way to configure URL rewrites (I haven't written mod_rewrite modules,  so those of us who have used it may find it simpler enough).

  1. The application-context is not part of your from element in the rule. I did not figure this out initially, but later when I removed it, the redirects were happening properly. So specify only the part after application-context that you want to rewrite, e.g. for rewriting http://localhost:8080/<APP>/Screen1, specify a pattern that includes just /Screen1 and rewrite to the in-built variable %{context-path}.
  2. Use a simple regex pattern like the one below to exclude static content from the application of the rules.  e.g. ^/(?:(?!images|scripts|styles).)+$ excludes all URLs of the form /<APP-CONTEXT>/images, /<APP-CONTEXT>/scripts and /<APP-CONTEXT>/styles normally and does not do any redirects for these static content.
PS: Please leave your comment on this post (as long as it is not abusive ;)), as it will help me understand the usefulness.

Related Articles

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.

Followers