16 October 2006, Darrell @ 11:00 am

I found out some of the great mystery of mod_rewrite. Here’s an example that works. Turns out there are errors in the documentation, of course, and this article may help avoid the pitfalls that I have discovered.

Here’s an .htaccess file that works for the example that is included here:

# Turn the re-write engine on so it rewrites URLs
RewriteEngine On
# not needed since we are sending URLs back to this same directory
#RewriteBase /test-rewrite/
# if the URL does not point to a file
RewriteCond %{REQUEST_FILENAME} !-f
#and if the URL does not point to a subfolder
RewriteCond %{REQUEST_FILENAME} !-d
# be tolerant of trailing slashes or not
RewriteRule ^products$ products/ [NC]
# and if there is no product specified, list them all
RewriteRule ^products/$ /content.php?action=product_list [NC]
#products can have a code and a subcode
RewriteRule ^products/([0-9]+)/([0-9]+)$ products/$1/$2/ [NC]
RewriteRule ^products/([0-9]+)/([0-9]+)/$ /content.php?code=$1&subcode=$2 [NC]
#or if we specify the code only, then forget the subcodes and list all the products in that code
RewriteRule ^products/([0-9]+)$ products/$1/ [NC]
RewriteRule ^products/([0-9]+)/$ /content.php?code=$1 [NC]

I discovered a bunch of rules that are not stated explicitly:

  • In RewriteRule, no slashes in patters after the ^
  • Slash at the beginning of the target after the pattern.
  • In a RewriteRule to make slashes optional, do not use [R] as the doc says. It doesn’t work.

The example that’s included here does work. It’s been tested. Unlike most of the rest of the examples out there. Sigh… :(


Apache Mod_Rewrite Example


No Comments

Sorry, the comment form is closed at this time.

Windy Weather is based on
WordPress platform, RSS tech , RSS comments design by Gx3.

27 queries. 0.339 seconds.