假设我有以下可用的 GET 变量:
状态
城市
卧室
浴室
类型
价格
现在我希望他们像这样出来:
mysite.com/state/city/#-bedrooms/#-bathrooms/type/price
但是,我希望它能够工作,这样如果这些变量之一不存在,它仍然可以工作
即:
mysite.com/state/city/#-bedrooms
或:
mysite.com/state/#-bedrooms/price
我该怎么做?
您可以使用
?
量词将正则表达式的某些部分设为可选。
# 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
但是,如果子模式不匹配,这将重写为空变量。
所以也许你应该定义一个具有不同特异性的 RewriteRules 列表:
RewriteRule ^(\w+)/(\d+)-bedrooms$ scr?state=$1&bed=$2
RewriteRule ^(\w+)/(\w+)/(\d+)-bedrooms$ scr?state=$1&city=$2&bed=$3
...
在代码中正确执行要容易得多:
#.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ /index.php [QSA,L]
您可以使用任何您想要的逻辑来处理请求 URI:
#index.php
<?php
$request = explode('/', ltrim($_SERVER['REQUEST_URI'], '/'));
$state = array_shift($request);
$city = array_shift($request);
// and so on