
Jul 09
PHP URL Rewriting Without Apache and mod_rewrite
Prior to launch I encountered a few problems;
- The server was IIS
- The server had no rewrite modules/filters for IIS
- 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.
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; } ?> |








SMS 8 December 2009 7:15 pm
good but you will have delay in response.
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.
Redirect Old Domain Names with Apache htaccess File › Daniel Gibbs Journal 14 April 2010 3:56 pm
[...] 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 [...]