mod_rewrite example

This is a port from the old Robertdot.

At work, we started using a redirect method with mod_rewrite that allowed us to send all file requests to a file called _process_me.php. This gave us tons of flexibility, allowing us to even make pages on the fly. If you can’t imagine why anyone would do this, imagine serving a page that doesn’t exist, assembled completely on the fly, without the user knowing. If you don’t get it yet, press ALT+F4 or COMMAND-Q right now for more information.

I really wanted to make use of this on my personal site. However, both my Mac and Delta Web Hosting were being major headaches. So, I sat down tonight to figure out what the problem was. Since I didn’t play with the Apache Configs on either system, it was a bit of a mystery at first. Here is what I came up with (some of the code may have spaces that don’t need to be there… my text formatting system misinterprets stuff):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 # These are both required!
 Options +FollowSymLinks -Indexes
 
 # Give it a default file for kicks...
 DirectoryIndex index.html
 
 RewriteEngine on
 
 # Commented one is for live tests...
 #RewriteBase / robertdot_new/
 RewriteBase / ~robert/robertdot_new/
 
 # Forward blank requests to the default file
 RewriteRule ^$ index.html
 
 # This would forward requests from robertdot.org to www. robertdot .org
 #RewriteCond %{HTTP_HOST} ^robertdot.org$ [NC]
 #RewriteRule ^(.*)$ http: //www .robertdot.org/$1 [R,L]
 
 # If the filename is not a valid directory, set the redirect flag to true
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^.* - [E=HTTP_GO:1]
 
 # If the filename is not a valid file, set the redirect flag to true
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^.* - [E=HTTP_GO:1]
 
 # If the filename is a valid directory, set the redirect flag to true
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^.* - [E=HTTP_GO:1]
 
 # Forward everything except _process_me.php to _process_me.php
 RewriteCond %{ENV:HTTP_GO} ^1$
 RewriteCond %{REQUEST_FILENAME} !_process_me.php
 RewriteRule . _preprocess.php

So, for all you kiddies that were looking for mod_rewrite examples, there is a really good one. If you need more explanation of what is happening, just read the mod_rewrite documentation.

Tags:

Comments are closed.