Wednesday, September 26, 2007

URL Rewriting with mod_perl

mod_rewrite is one of the greatest modules for Apache web server. You can do almost anything with URLs of your website. Redirect old pages to new ones, reverse proxy to other server (requires mod_proxy too) or hide your ugly CGIs behind nice .html extentions.

But if you want to do somewhat more complicated rewriting (or just for the hell of it) you might want to consider writing your own Apache HTTPD module or use mod_perl. Here is how:
package My::URLRewrite;

my %URL_MAP = (
'/my/old/url' => '/my/new/url',
'/other-url' => '/another/one',
);

sub handler {
my $r = shift;

# Search the URL map
for my $url (keys %URL_MAP) {
if ($r->uri eq $url) {
# Found one, rewrite it
$r->url($URL_MAP{$url});
return Apache2::Const::DECLINED;
}
}

return Apache2::Const::DECLINED;
}
Color by Colorer-take5 HTML generator
Now the last trick is the appropriate Perl handler: PerlTransHandler

Once you add this to your server configuration give it a whirl. Of course this is only a simple example. Nothing would stop you from reading the map from a database or reading them from your Google Spreadsheets or even correcting spelling mistakes (although you might want to use mod_spelling there - hang on - mod_spling - no, no - mod_speling).

No comments:

Post a Comment