Short URL redirects in Expression Engine, without add-ons

Today I had the need to create custom short URLs for a client. They wanted a single keyword as the short URL. I first looked into the Shrimp plugin, and then the Redirect301 plugin, but both relied on creating a new template group with a single character name, such as "u", which ends up with URLs like mysite.com/u/123. While this was close to what I needed to achieve, it wasn't a viable solution because of an unnecessary extra URI segment.

After a little creative thinking, and taking advantage of Expression Engine's flexibility I came up with a solution... Create a new template group called Redirects, with the short name redirects. Turn off Strict 404s, and create 2 new templates, one to be the actual 404 page you want to serve, and the other being the interstitial one that will be assigned as the 404 page in Expression Engine, in my example I chose 404_catch. What this will do is any time Expression Engine can't find a requested page, it will load the 404_catch template, which includes the following template code that first searches the redirects Weblog for any entries with a slug value the same as the first URI segment. If none is found, then it will then redirect to your actual 404 page, but if one is found, it will redirect to the URI you defined in the entry. It may be a good idea to disable most of the tabs in the Publish page, just because they're unnecessary, and to disable options such as field formatting, and even the URL Title field. I chose to prefix every entry in the Redirects weblog with redirect-.

I believe another way to accomplish is to use the Pages module, and create a single segment page for an entry, but since I'm already using Structure to manage my pages, this wasn't an option. I also have about 10 different content types, and a couple of URI patterns used on the site, so I needed a solution that wouldn't interfere with Structure, and be flexible enough to work with any URI pattern. Unfortunately there is no way to prevent duplicate entries of the same URL slug, so that is a big caveat, but in my client's case, they won't have hundreds or thousands of these short URLs. If a duplicate comes up, it should be easy to notice the issue and change the URL slug.

site/404_catch template{exp:weblog:entries weblog="redirects" disable="pagination|categories|member_data" limit="1" search:redirect_slug="{segment_1}"} {if no_results} {redirect="site/404"} {/if} {redirect="{redirect_url}"} {/exp:weblog:entries}

Disable all unnecessary Publish form options.

Create a Redirect.

Setup the 404 page you want to use.

Posted on: Tuesday, September 29, 2009