Not so long ago I wrote about my experiences on getting Railo running on under OS X as a test. Along with just getting Railo running as well as a custom CMS I needed to be able to proxy requests through an Apache server to the Railo application server. One method is to use the simple mod_proxy module available as part of Apache. In my setup I wanted a bit more control than what mod_proxy could provide me. Enter mod_rewrite.

Mod_rewrite is used to manipulate URLs as they enter and pass through Apache. One way mod_rewrite is useful is that it allows you to rewrite incoming URLs so that what the user sees in their browser’s location bar is translated into what the application expects. You can also use it to manipulate the URL in the event that the location of an object has changed. In my setup I wanted to use mod_rewrite to rewrite certain URLs and then proxy them through the Railo application server.

Lets say my Railo application lives at http://localhost:8080/ and I want any URL that comes into Apache (on port 80) that starts with a keyword like ‘show’ to be rewritten and passed to Railo. Railo could just as easily be hosted on some other machine but for this example lets just say it is located on the same system as Apache.

In my example, I have a new vhost configured in Apache and it looks like this:

  <VirtualHost *:80>
    ServerName railo.dustinrue.com
    DocumentRoot "/Users/dustin/Sites/railo.dustinrue.com"
    <Directory "/Users/dustin/Sites/railo.dustinrue.com">
      RewriteEngine On
      RewriteRule ^show/(.+)$ http://localhost:8080/index.cfm?url=/show/$1} [P]
    </Directory>
  </VirtualHost>

Notice that I’ve told mod_rewite that I want to use an external command for rewriting the incoming URL. An external program basically accepts one argument, which is the URL portion that matches the rewrite rule, and then prints out the reformatted URL which Apache then uses from that time on and in this case, passes to Railo.

In this example, mod_rewrite will take a URL that might look like:

http://railo.dustinrue.com/show/article/id/123456/

And turn it into:

http://localhost:8080/index.cfm?url=/show/article/id/123456/

At the end of the mod_rewrite rule you see a flag telling mod_rewrite to proxy the request through the rewritten URL rather than giving than than telling the browser to visit the new URL (the default behavior). In turn, the request comes into Apache which sees the ‘show’ keyword. This keyword causes the request to be passed to the application server which responds with the appropriate output and this output is then sent to the browser.

In my example, the rewrite is very simple. You can do far more advanced stuff than this and it’s even possible to do some rewriting right within Railo and the server it is running under such as Jetty or Tomcat.