conditional htaccess?

爷,独闯天下 提交于 2019-12-25 08:46:33

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/6326477/conditional-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!