conditional htaccess?

2019-09-02 02:24发布

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?

2条回答
时光不老,我们不散
2楼-- · 2019-09-02 02:50

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
查看更多
爷的心禁止访问
3楼-- · 2019-09-02 02:53

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
...
查看更多
登录 后发表回答