The Definitive Guide to Apache mod_rewrite (Definitive Guides (Hardcover))

Category: Programming
Author: Rich Bowen
This Year Stack Overflow 2
This Month Stack Overflow 1


by anonymous   2017-08-20

Strangely enough,

RewriteRule   ^/help    help.php?q=2              [L]

The above rule fails and never matches.

This rule:

RewriteRule   ^help      help.php?q=1             [L]

Matches http://localhost/help, http://localhost//help and http://localhost///help

It appears RewriteRule never sees leading slashes of the path, and as TheCoolah said they are collapsed (to 0.. when using a .htaccess file anyway) no matter how many there are.

For the second part of the question,

RewriteRule   ^help    /help.php

I'm getting the answer from Definitive Guide to Apache Mod_rewrite

... a rewrite target that does not begin with http:// or another protocol designator is assumed to be a file system path. File paths that do not begin with a slash are interpreted as being relative to the directory in which the rewriting is taking place.

So /help.php looks in the root of the system for a file called help.php, which on my system it cannot find.

To make /help.php appear as a relative URL (relative to the root of the site) you can use the [PT] directive:

RewriteRule   ^/help    /help.php    [PT]

That directs http://localhost/help to http://localhost/help.php.

by anonymous   2017-08-20

Put the rules below at the top of your .htaccess file (in the root directory of your site) and then select one of the options below, modify it to your needs and place in after in your .htaccess file.

The first option will match the most urls and is not recommended. The second will only match urls with 5 directories, but requires all the paramters, so I recommend the 3rd.

Though the pattern below may not look elegant, it is a featured solution in The Definitive Guide to Apache mod_rewrite

For more details look at the apache docs or some examples or this post

In all cases, I am assuming that the requests go to index.php, so you should modify this to match the actual page.

This section should go at top of .htaccess file for all 3 options

#for all 3 options these 2 lines should be at the top of the .htaccess file
RewriteEngine On
RewriteBase /


#1 if all parameters are optional, and you page (index.php) can handle blank parameters use
RewriteRule ^([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/$ index.php?module=$1&q=$2&shortBy=$3&catID=$4&searchIn=$5 [L]


#2 if all parameters are required use
RewriteRule ^([^/]+)/([^/]+)/([^/]+)?([^/]+)/([^/]+)/$ index.php?module=$1&q=$2&shortBy=$3&catID=$4&searchIn=$5 [L]


#3 if the module is required and other parameters are optional, then this is better
RewriteCond %{REQUEST_URI} ^/(search|produce_detail|other_modules_here)/
RewriteRule ^([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/$ index.php?module=%1&q=$1&shortBy=$2&catID=$3&searchIn=$4 [L]