November 10, 2011

Apache Query String URL to SEO Friendly URL

On one of my current migration projects. I need to rewrite a bunch of clunky old dynamic query string URLs to nice clean search engine friend URLs. Took a bit of digging through Apache documentation, but here it is.

The goal was to go from

http://domain.tld/?tag=somekeyword&Template=feed&IncludeBlogs=71

to

http://newdomain.tld/feeds/topic/somekeyword/

If you want to rewrite just one URL, simply type it in as written below. The downside to this approach is that, it’s just one URL. You would have to retype this for each string you wanted to rewrite.

RewriteEngine On
RewriteCond %{QUERY_STRING} ^tag=blah&Template=feed&IncludeBlogs=71$
RewriteRule ^index.php$ /feeds/topic/blah/? [L,R=301]

Or if you want to get fancy and some piece of the original URL actually matches the new URL, You can store it and then :

RewriteEngine On
RewriteCond %{QUERY_STRING} ^tag=([a-z]+)&Template=feed&IncludeBlogs=71$
RewriteRule ^index.php$ /feeds/topic/%1/? [L,R=301]

In both examples, index.php is an example and would be whatever your script address is.