URL rewriting using database values

If anyone can help I’d really appreciate it…

I’ve created a relatively simple CMS for a client giving them the ability to add their own search engine friendly URLs. These are stored in a MySQL database.

I know how to do URL redirects using static values in .htaccess, but is it possible to use the values stored in a database?

I don’t think .htaccess can interact directly with the database (if it can that would be simpler), so does anyone know if there’s a way to this via a php script.

To give you an idea, I want to change this URL…


to this…


Many thanks

You could also take a look at mod_rewrite’s RewriteMap, though this is kind of hard to set up. johnyboy’s suggestion is probably easier :slight_smile:

make your .htaccess file point all accesses to one catch all script. in that script get the requested url, do your database look up etc, then include() the required file.

do a search in the php applications forum on here for ‘router’ and you’ll get more on it – there’s been at least one thread about doing that there, probably more.

This is quite easy to handle with apache’s mod_rewrite feature.

First of all you must construct your LINK/URLs with the keys from the database. Like when you want to have a URL in the About Us link then you must query it’s corresponding SEF key from the datatabase.

<a href="http://www.yourdomain.com/about-us.html">About Us</a>

I think this is quite possible to get the SEF key from database and use it in the URL.

Now you must instruct apache to work as per your requirement. So create a file named .htaccess in your root folder/directory and paste the following code in it:

RewriteEngine on

RewriteCond &#37;{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^/?(.*)\\.html/?$ content.php?sefkey=$1 [L]

And now in your content.php, you will have the key of the content as about-us which must be UNIQUE in the database so that you can query ChildID and ParentID of that content from the database.

$sefkey = mysql_real_escape_string($_GET['sefkey']);
    $result = mysql_query("SELECT ChildID, ParentID FROM contents WHERE sefkey='" . $sefkey . "'") or die(mysql_error());
    if(mysql_num_rows($result) >= 1){
        $content = mysql_fetch_object($result);
        $_GET['ParentID'] = $content->ParentID; 
        $_GET['ChildID'] = $content->ChildID;
        die('Invalid SEF Key'); // or handle the situation here...
    header("Location: index.php");

None of the code above are tested for this particular case but I hope this will work for you. Hope you can manage as said.