scarhand
scarhand

Reputation: 4337

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?

Upvotes: 1

Views: 514

Answers (2)

sanmai
sanmai

Reputation: 30881

It is much easier to do right in your code:

#.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ /index.php [QSA,L]

You can use whatever logic you want to process the request URI:

#index.php
<?php
$request = explode('/', ltrim($_SERVER['REQUEST_URI'], '/'));
$state = array_shift($request);
$city = array_shift($request);
// and so on

Upvotes: 1

mario
mario

Reputation: 145482

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
...

Upvotes: 1

Related Questions