Remove empty parameters from URIs
Tuesday, October 10th, 2006I recently re-designed the Koha advanced search form for the new API and discovered that it was very difficult to avoid submitting lots of empty parameters with every form submission (this is a very large form with lots of dropdown and checkbox options). The problem is that all those empty parameters really clutter up the URI. So for example, you might just be doing a simple keyword search on Neal Stephenson, but the URI might look something like:
/search?idx=&op=and&q=neal stephenson&limit=&limit=&limit=&sort_by=&num_of_results … you get the picture. So how does one go about cleaning that mess up? I’ve found a couple simple ways to do it, one relies on parsing the URI in the Perl script, removing the empty parameters, and then redirecting the user to the newly formed URI. The other works the same way, but uses mod_rewrite. Here’s some code:
The Perl Way
# first step: find the URI base
my $uri = $cgi->url(-base => 1);
my $relative_url = $cgi->url(-relative=>1);
$uri.=”/”.$relative_url.”?”;
#warn “URI:$uri”;my @cgi_params_list = $cgi->param();
my $url_params = $cgi->Vars;
for my $each_param_set (@cgi_params_list) {
$uri.= join “”, map “\&$each_param_set=”.$_, split(”\0″,$url_params->{$each_param_set}) if $url_params->{$each_param_set};
}
warn “New URI:$uri”;
# Only re-write a URI if there are params or if it already hasn’t been re-written
unless (($cgi->param(’r')) || (!$cgi->param()) ) {
print $cgi->redirect( -uri=>$uri.”&r=1″,
-cookie => $cookie);
exit;
}
The mod_rewrite way
RewriteEngine On
RewriteCond %{QUERY_STRING} (.*?)(?:[A-Za-z0-9_-]+)=&(.*)
RewriteRule (.+) $1?%1%2 [N,R,NE]
My personal preference is the mod_rewrite method. It’s shorter
. Also, I’m much more comfortable leaving the logic of rewrites at the web server level rather than messing around at the application level.
If you want to see this recipe in action, check out the Nelsonville Public Library catalog:
http://search.athenscounty.lib.oh.us
Any URI re-writing recipes you’d like to share? Comments, questions?