Monday, 30 September 2013

GET data with htaccess URL rewrite?

URL rewriting is one of the best way to create SEO friendly URL for your site.

Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7

http://www.yourdomain.com/product.php?product_id=7

The problems with this kind of URL structure are that the URL is not at all memorable and not SEO friendly also.
In case of dynamic pages created by admin (product.php?slug=productname) or pages with query string you have to redirect that dynamic page to a existing page let's say "get-product.php" here you can get the slug value (query string value) by using PHP $_GET['slug'](super global variable) by the help of that variable you can fetch corresponding data from database.

Note: create a unique slug  from the title field for fetching data from database.

Write following code in .htaccess file for url rewrite of dynamic generated file.

RewriteEngine on
RewriteRule ^([A-Za-z0-9]+)\.php get-product.php?slug=$1 [NC,QSA,L]

Note: here we added some flags at the end of RewriteRule.
  • NC (case insensitive)
  • QSA (append query string from request to substituted URL)
  • L (last - stop processing rules)
Now go to "get-product.php" file write following code.

<?php print_r($_GET);?>

Output
Array ( [slug] => productname )

No comments:

Post a Comment