April 3, 2012

url rewriting by .htaccess files in php

Question by Code Road

I am rewriting my problem .
Below I am giving all the details of what i am trying to do, and what is the result I am getting. I hope to be very clear this time. I have a samples page here www.broadcast2world.com/samples.php.
All the links and data which we see on the page is coming from a database. Now suppose we click on a link “More Info” for a particular video say social control. A specific href for that video is triggered as <a href="video.php?pid='.$id.'"> . It passes its id over url in the format http://www.broadcast2world.com/video.php?pid=66.

I catch that id into a variable using

if(!isset($_GET['pid'])){
    $pageid='66';
}
else{
  $pageid=$_GET['pid'];  
} 

Using the $pageid variable, I run a query which ultimately prepare the page for that particular video.

What my SEO guy need is a url in the format www.broadcast2world.com/video/name-of-the-video.

Now the problem is that if I make a mod_rewrite amendments which is wonderfully explained by Ben below, I am not able to figure out, how to link that name-of-the-video to its id. I am sure there must be something I have to modify while creating specific url for videos as explained above. But I really don’t know what? Thanks again for your wonderful support

Answer by Starx

Instead of id, you have to search the database based on title then.

Here are what you are going to need.

.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^videos/(.*)$ video.php?title=$1

Link generation

$title = "...";
$title = str_replace(" ", "-", $title); //add dashes on the link
echo "<a href="videos/$title">Click Me</a>";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!