Nice, SEO-friendly URLs in Catalyst application

I really enjoy power behind Clean URLs in Drupal CMS. It allows me instead of "http://www.example.com/node/123" path to have nice URL like "http://www.example.com/blog/nice-seo-friendly-urls-in-catalyst-application". And most important I can change this nice url to whatever I want or need.

I found it is quite easy to implement something similar for Catalyst application.

I store url aliases in table url_aliases (url_alias_id, internal_url, external_url). Where internal_url - Catalyst internal action path, external URL - everything you see in address bar after http://www.example.com/

In my default action in Root.pm (which normally shows 404 error page) I added few lines of code:

  my $url_alias = $c->model('DB::UrlAlias')->search({ external_url => $c->req->path })->single; 
 
  if ($url_alias) { 
      $c->go( '/'. $url_alias->internal_url ); 
  }

And here is my MyApp::Schema::Result::UrlAlias result class for a reference:

package MyApp::Schema::Result::UrlAlias;
 
use strict;
use warnings;
 
use base 'DBIx::Class::Core';
 
__PACKAGE__->table("url_aliases");
 
__PACKAGE__->add_columns(
  "url_alias_id",
  { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
  "internal_url",
  { data_type => "varchar", size => 1024, is_nullable => 0 },
  "external_url",
  { data_type => "varchar", size => 1024, is_nullable => 0 },
);
 
__PACKAGE__->set_primary_key("url_alias_id");

Now you can add something like this into DB:

INSERT INTO (url_alias_id, internal_url, external_url) VALUES (1, 'index', 'homepage');

And you should be able to access your /index action via http://www.example.com/homepage URL.

Next would be to add caching to eliminate repetitive requests to DB, add secondary indexes for internal_url and external_url fields and add some UI to edit these settings.. But overall it was very easy. :)

Tags: