Subscribe:

May 8, 2006

Mod Rewrite Script

Filed under: Misc,Web Technologies — Scott @ 4:42 pm
Add

About 3 years ago I wrote a function that makes rewriting urls relatively easy. My problem at the time was how to convert a phpbb forum to use search engine friendly urls. The solution I came up with makes it easy to convert php scripts to use mod rewrite without having to go to great lengths to rewrite the urls in your .htaccess file. The solution does all the processing in the php script with the addition of a simple function.

Get the Easy Mod Rewrite solution.

Full explantion of the mod_rewrite() function:


In the .htaccess you have:

RewriteEngine On
RewriteBase /
RewriteRule ^somepage/(.*)\.html somepage.php?rewrite=$1 [L]

Your links:

Your original link url was: http://yoursite.com/somepage.php?id=20&name=funny

You change your url to: http://yoursite.com/somepage/id-20/name-funny.html

In the script somepage.php you put this at the top:

< ?php

if( $_GET['rewrite'])
{
$request = $_GET['rewrite'];
mod_rewrite( $request, ‘/’, ‘-’ );
# if you have register_globals enables uncomment the following
# extract( $_GET, EXTR_OVERWRITE );
}

?>

What happens when a user clicks the link:

User sends request for “somepage/id-20/name-funny.html”

ModRewrite Engine is on and request matches pattern matches “somepage/”

ModRewrite engine changes the request to somepage.php?rewrite=id-20/name-funny

The PHP engine is called and the script is run

the $_GET['rewrite'] is processed by the mod_rewrite function

the mod_rewrite function changes this value “id-20/name-funny” into

$_GET['id'] = ’20′;
$_GET['name'] = ‘funny’;

then if you depend on register_globals being on ( read converting an old script )
you call this:

extract( $_GET, EXTR_OVERWRITE );

right after the mod_rewrite function to put all the new $_GET variables into the global name space

viola !
mod_rewrite made relatively easy

Popularity: 10% [?]


Like it? Subscribe to the blog if you haven't already
Digg!

Related Posts


RSS feed

3 Comments »
Comment by Avaranger
2006-09-06 06:03:15

How the hell can I make the rewrite not behave like directories. I wanna have sth.com/page/sub/ but it ruins my links!

 
Comment by Scott
2006-09-06 10:33:21

Not sure what you need Avaranger, in general you should 301 your old links to your new setup IMO.

 
Comment by skylla
2006-11-27 19:34:08

Hello Scott,

What is possibly going wrong when the ‘rewrite’ index remains undefined?

reg_globals is off and I believe the RewriteRule in .htaccess to be correct:

RewriteRule ^index/(.*)\.html index.php?rewrite=$1

Thanks for your help…

cheers.

 
Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.