Forum Moderators: phranque

Message Too Old, No Replies

How to add a backslash via mod_rewrite

         

voltrader

2:31 am on Oct 19, 2005 (gmt 0)

10+ Year Member



This is my current script:

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*)/(.*)/(.*)/(.*)/$ /browse/index.php?y=$1&s=$2&c=$3&p=$4

If somebody leaves the last backslash off, like:

/browse/1/2/3/4

the user is sent to my 404 page

The page only resolves when the backslash is included like:

/browse/1/2/3/4/

What can I do here?

jdMorgan

2:37 am on Oct 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Make the final slash optional using the "?" regex token:

RewriteRule (.*)/(.*)/(.*)/(.*)[b]/?$[/b] /browse/index.php?y=$1&s=$2&c=$3&p=$4

For more information, see the documents cited in our forum charter [webmasterworld.com] and the tutorials in the Apache forum section of the WebmasterWorld library [webmasterworld.com].

Jim

voltrader

3:09 am on Oct 19, 2005 (gmt 0)

10+ Year Member



Thanks JD - appreciate the help

voltrader

3:39 am on Oct 19, 2005 (gmt 0)

10+ Year Member



RewriteRule (.*)/(.*)/(.*)/(.*)/?$ /browse/index.php?y=$1&s=$2&c=$3&p=$4

Adding the? in the 1st clause somehow messes up the variable order. y disappears. Does it think there are now 5 variables?

Thanks for the links -- I read through it and still absorbing it.

jdMorgan

4:53 am on Oct 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Oh yeah, greedy and ambiguous ".*" patterns will cause that problem. See if this will work with your URLs:

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /browse/index.php?y=$1&s=$2&c=$3&p=$4

The pattern "[^/]+" means, "one or more characters not equal to a slash," whereas ".*" means, "any number -including zero- of any characters" (which could include the slash).

Jim

voltrader

4:08 am on Oct 25, 2005 (gmt 0)

10+ Year Member



Thanks again jd -- I was experimenting ad nauseum and would not have figured that out!

jdMorgan

2:06 pm on Oct 25, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm on a one-man crusade to banish the use of the ".*" pattern from mod_rewrite code. It is greedy, ambiguous, and inefficient, and causes all kinds of subtle problems. The trouble, though, is that it seems 'easy' and 'familiar' because it resembles the old DOS file wild-card "*.*". But in mod_rewrite, it will match anything and everything, and leave adjacent patterns to 'starve'.

In almost all cases, mod_rewrite code will work better and *much* more efficiently if a more-specific pattern is used. There are situations that require the use of ".*" but it is best if used sparingly and only when necessary.

Jim