php icon
15th
Jul 09

PHP URL Rewriting Without Apache and mod_rewrite

Recently I was put in a situation where I had created a dynamic site that, prior to launch, needed Search Engine Friendly (SEF) URL’s.

Prior to launch I encountered a few problems;

  1. The server was IIS
  2. The server had no rewrite modules/filters for IIS
  3. I had extremely limited access to H-Sphere (a control panel)

At that point I started being concerned about the deadline especially after the amount of time and effort put into developing the site. I took a 10 minute break and tried thinking of a solution.

I don’t recommend using the approach I’m about to explain unless it’s necessary and you’re in a situation like I was with no alternative.

Through H-Sphere I was able to set up a custom error page. I decided to create a PHP script as the error page and used that as my “rewrite” method (it’s technically not rewriting but still). I didn’t want the script to re-direct the user, that would defeat the point of doing this, and after checking the server wasn’t sending a 404 header and decided to do it.

For example we have a link on our page that points to “some-nice-page.htm” which doesn’t exist on the server. We direct the server to the PHP script, check it’s a valid dynamic URL (?id=some-nice-page) and include the content/dynamic page.

PHP URL Rewrite Method

PHP URL Rewrite Method

Using PHP we can get the requested URL with the REQUEST_URI server variable. Below is a quick (and untested) example of how you could create your 404 script.

An example of 404script.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
// Explode the URI into an array via /
$script = explode("/", $_SERVER['QUERY_STRING']);
 
/*
Get the end of the URL - This may need changing
especially if the URLs are in a directory style format
i.e. www.mywebsite.com/category/page/ 
*/
$page = explode(".", $script[(sizeof($script) - 1)]);
 
if ($page[0] == "")
{
	// Nothing set, the homepage?
	header("Location: http://www.website.co.uk");
}
else
{
	// Set the URI variable and use it in index.php to determine the rest
	$uri = $page[0];
	include("index.php");
}
?>

An example of index.php using the variable $uri

1
2
3
4
5
6
7
8
9
10
11
12
<?php
// If the URI hasn't been set then set it
if (!isset($uri)) $uri = $_GET['id'];
 
switch($uri)
{
	// SERVICES
	case "services": 
		// Do the services page
		break;
}
?>
SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon

Related posts:

  1. URI Rewriting Alongside WordPress’ PermaLinks


3 Comments

  1. SMS 8 December 2009 7:15 pm

    good but you will have delay in response.

  2. Gibbs 17 December 2009 5:51 pm

    Very true SMS but on a small or medium sized static site it the delay should be unnoticed.

  3. [...] likely need to look into using mod_rewrite (the rewrite module for Apache servers). You can also rewrite URLs with PHP (although I don’t recommend [...]

TrackBack URL

Leave a comment