Tuesday, 12 July 2011

How to hide query string in url with a .htaccess file

To masquerade the query string into a pretty SEO url you can use Apache's mod_rewrite.
Rewrite rules don't actually hide the query string, rewrite rules pretty much convert SEO friendly urls into the actual query string.

Example .htaccess:
RewriteEngine on
RewriteRule ([a-zA-Z0-9_]+)\.html$ viewPage.php?ID=$1 [L]
The above rewrite rule will allow you to do something like this:

url reads: yoursite.com/test.html
apache interprets as: yoursite.com/viewPage.php?ID=test
Therefore the following PHP code:
echo $id;
will output test.

What if we want to pass more than one value, like "yoursite.com/viewPage.php?ID=test&category=coding" ?

We just have to convert /categories/coding/test.html into /viewPage.php?category=coding&ID=test

This will do the trick:
RewriteEngine On
RewriteRule ^categories/(\w+)/(\w+)\.html viewPage.php?category=$1&ID=$2 [L]

Possibly Related Posts

No comments:

Post a Comment