Search code examples
.htaccessmod-rewrite

conditional htaccess?


lets say i have the following GET variables available:

state

city

bedrooms

bathrooms

type

price

now i want them to come out like this:

mysite.com/state/city/#-bedrooms/#-bathrooms/type/price

however, i want this to work so that if one of these variables are not there, it will still work

i.e.:

mysite.com/state/city/#-bedrooms

or:

mysite.com/state/#-bedrooms/price

how do i do this?


Solution

  • You can make parts of a regex optional using the ? quantifier.

                # state   city       bedrooms              bathrooms
    RewriteRule ^(\w+)(?:/(\w+))?(?:/(\d+)-bedrooms)?(?:/(\d+)-bathrooms)?$
                script.php?state=$1&city=$2&bedrooms=$3&bathrooms=$4
    # add further (?:(\d+)-placeholders)? for the other optional parts
    

    This will however rewrite to empty variables if a subpattern is not matched.

    So maybe you should rather define a list of RewriteRules with varying specificness:

    RewriteRule ^(\w+)/(\d+)-bedrooms$ scr?state=$1&bed=$2
    RewriteRule ^(\w+)/(\w+)/(\d+)-bedrooms$ scr?state=$1&city=$2&bed=$3
    ...