Forum Moderators: phranque

Message Too Old, No Replies

optional multiple variables using single RewriteRule

mod_rewrite RewriteRule apache

         

an15h

5:32 am on Oct 15, 2010 (gmt 0)

10+ Year Member



hi all...

i had been refering webmasterworld [webmasterworld.com] for apache related stuffs.

yesterday i came across this post optional multiple variables [webmasterworld.com]

the author wanted to rewrite
http://www.example.com/index.php?market=$1&product=&2&subcat=$3


all the variables were optional.

the solution given was:
You will either need to use a separate rule for each possible combination of present/not-present path-values, or us a single rewriterule with a specific RewriteCond for each possible combination of present/not-present path-values.

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$ index.php?m=$1&p=$2&s=$3 [L]
RewriteRule ^([^/]+)/([^/]+)/$ index.php?m=$1&p=$2 [L]
RewriteRule ^([^/]+)/$ index.php?m=$1 [L]


is it possible to rewrite this using a single rewrite like:

RewriteRule ^([^/]+)(/?)([^/]+)(/?)([^/]+)/$ index.php?m=$1&p=$3&s=$5 [L]

and in the server-side code(php etc.), make a condition for if m='', p='', and s=''

my understanding is that it's better to keep rewrite rules to a minimum. so by making the rewriterule for optional variables like this, will it help?

g1smd

7:05 am on Oct 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In this case, for the URL "example.com/keyword" the result would be m="keywo" p="r" and s="d".

an15h

10:19 am on Oct 15, 2010 (gmt 0)

10+ Year Member



@g1smd: are you sure that "example.com/keyword" leads to m="keywo" p="r" and s="d"

leaving this aside, what is your opinion about adding (/?) for optional multiple variables?

i'm asking this because, in another site, in an example i found out there were 7 optional variables, and 7 RewriteRules

an15h

10:32 am on Oct 15, 2010 (gmt 0)

10+ Year Member



@g1smd: i guess you are right. (/?) might lead to problems

jdMorgan

6:46 pm on Oct 15, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The multiple-rule approach is preferred because it is simplest and easiest to maintain.

There are other solutions, but all of them make my brain hurt, even though the goal is trivial, and it usually takes an awfully-complex chunk of code to make my brain hurt... :)

Jim