Tuesday, August 11, 2009

Dynamic Redirects

Have you been in the situation where you want to shorten URL's in your communication? For instance, it is time for a new Magnolia newsletter, the 8th one in our series. Our newsletters are located at http://www.magnolia-cms.com/home/news/newsletters/newsletter-8.html - not exactly brilliant from a communications perspective.

Magnolia allows you to add VirtualURIRedirects, and I have written about their usefulness before in the context of site restructuring.

For our newsletter, we typically add an entry in the configuration like this:

In other words, we add a static entry that forwards www.magnolia-cms.com/nl8 to our newsletter location deep within the site hierarchy, and makes it much easier to send out links or twitter about it.

So far so good, but today saw the 8th time I needed to add such an entry; and what is worse, I realized that we forgot the redirect for our 7th newsletter (which was sent out while I was on holidays, and the person doing the job did not know he had to add it).

Time to dig a little deeper into Magnolia, and avoid future work and worries!

Since sometime in Magnolia 3, you can use regular expressions in the VirtualURIMapping configuration. Here is what you need to do

  1. copy an existing configuration
  2. instead of the default class (aptly named "DefaultVirtualURIMapping") use the class RegexpVirtualURIMapping
  3. define your match ("fromURI"), in our case "/nl([0-9]+)$" which means any URI starting with /nl followed by digits and nothing more (the $ means end of line). The parenthesis denote the dynamic part, which we need to determine the correct destination in the last step:
  4. define your target ("toURI"), in our case the newsletter page deep within the hierarchy, with an added twist: we dynamically add our match to the page name, i.e. "newsletter-$1.html". In this case $1 means replace "$1" with whatever was matched in step 3 between the parenthesis. (And yes, you can have more than one set of parenthesis and reference the matches with $1, $2 etc).
The resulting entry should look as follows, and all you need to do now is activate your configuration and enjoy!

As you can imagine, this is also great for search-engine optimized landing pages.