mod_rewrite example
Posted by Robert on the 27th of June, 2005 at 12:16 AM GMT0. Permalink.Tags: Apache, mod_rewrite, PHP, Random, Web Design
The following is an advertisement.
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):
# 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.
Add this page to del.icio.us or email it.
Comments on this page are closed due to age. If you need to say something, e-mail me.