Brian Tanaka

Web Application Development for businesses large and small...

Blog Home | 2010 Archive | 2009 Archive | 2008 Archive

Wed, 16 Jul 2008

The problem -- You have an HTML form whose action points produces a GET URL like this: http://example.com/foo.php?s=bar+baz but you want to redirect it to a flat directory style URL like: http://example.com/bar+baz

The solution -- Use Apache's mod_rewrite. In your .htaccess file do this:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{QUERY_STRING} ^s=(.*)$
RewriteRule .* /%1? [R,L]

How it works:

  • RewriteCond %{REQUEST_METHOD} GET - This is a get request, so make that a condition.
  • RewriteCond %{QUERY_STRING} ^s=(.*)$ - This condition says: "The query parameters begins with s and the value of s will be captured for later use."
  • RewriteRule .* /%1? [R,L] -- This rule says: "Redirect, replacing everything with a / followed by the value captured in the QUERY_STRING condition above, and if this rule succeeds, don't process any more rules.

Hope that helps someone out there. The important thing to remember here is that you have to match the name-value pair in the QUERY-STRING condition, not in the RewriteRule. If you notice anything incorrect about this solution and want to comment, send me an email and I'll post your comment as an addendum.

Posted at: 11:33 | [Path: /apache] | Permalink | Comments disallowed | Posts RSS