PHP rewrite

a simplified clone for mod_rewrite built in PHP

 

Introduction

mod_rewrite allows you to rewrite URL's on the fly, for example:

http://www.randombase.com/filehandler.php?id=154&pagenumber=445&title=Hello

will become

http://www.randombase.com/page/445/154/Hello.html

which is more search engine friendly.

The downside is that not all servers support mod_rewrite, and we're mainly speaking free or cheaper hosts here. PHP rewrite is used to achieve a similar effect, without all the extra's and advanced options mod_rewrite has, so this script is in no way a replacement of mod_rewrite for bigger websites that use it more intensively.

 

Installing PHP rewrite

The installation of PHP rewrite only takes a few minutes. Please follow these instructions.

1. Make a new .htaccess file or add this line to your existing one, in your www root (www/, htdocs/)

ErrorDocument 404 /php_rewrite.php

2. Upload the contents of the archive php_rewrite.zip to the same directory as where your .htaccess file is

3. Open rules.txt and add rules in a similar way as the example below.

pages/*/*.html page.php?id=$1&$title=$2 *.html page.php?id=$1&$title=$2

The structure is:

[BROWSER URL] [DESTINATION] [OPTIONS]

The wildcards (*) in the [BROWSER URL] will be replaced in the [DESTINATION] by whatever is typed into the browser. Don't add unnecessary spaces or anything or the script will BREAK. The [OPTIONS] is an optional argument. There are currently two available options: r and i. r means redirect, the script will redirect to the url instead of opening the page inside the script. i means cAsE InSeNsItIve, so page/blah.html will work the same way PAGE/blAh.html does. The following example will ignore the case on the first rule, redirect the second and do both on the third one.

article/*/*/*.html includes/articleparser.php?year=$1&title=$3&month=$2 i
store/linkexternal/* http://www.randombase.com r
store/errors/* contact.html ir

4. All done! If your rules are added correctly, you should be able to visit the URL's the way you want them.

 

Troubleshooting

During testing I found a common problem, where the wrong URL is rewritten. It's best to have a certain order in your rules file, by putting the most general rules on bottom. For example, put *.html index.php?p=$1 UNDER pages/*.html page.php?page=$1.

An other problem you may encounter is when you start working with subdirectories. Make sure you always put the FULL url after the website address in the rewrite rules. For example, if your website is johndoe.com and you wish to redirect johndoe.com/pages/external/* to janedoe.com, the rule would be NO MATTER WHAT DIRECTORY YOU ARE IN:

pages/external/* http://janedoe.com r

 

Download

PHP rewrite can be downloaded by clicking the button below, and is released under the Creative Commons license.