如何使用htaccess重写多个get变量

时间:2015-03-07 12:09:22

标签: php .htaccess mod-rewrite

我有一个带搜索表单的页面(字段:品牌,型号,年份,里程,价格) 在表单提交网址是:

http://www.example.com/buy-car.php?make=xxx&model=xxx&mileage=100;10000&year=2000;2015&price=20000;60000&sort=date;DESC

我想改写为:

http://www.example.com/buy-car/xxx/xxx/100;10000/2000;2015/20000;60000/date;DESC

注意:查询字符串可能包含也可能不包含所有变量

我尝试了多条规则,但仍然没有得到我想要的东西

RewriteCond %{THE_REQUEST} /buy-car\.php\?make=([^\s&]+)&model=([^\s&]+)&year=([^\s&]+)\&mileage=([^\s&]+)\&price=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1/%2/%3/%4/%5? [R=302,L]

RewriteRule ^buy-car/([\w-]+)/([\w-]+)/([\^;a-zA-Z0-9_-]+)/([\^;a-zA-Z0-9_-]+)/([\^;0-9-]+)/?$ buy-car.php?make=$1&model=$2&year=$3&mileage=$4&price=$5 [L,QSA,NC]


RewriteCond %{THE_REQUEST} /buy-car\.php\?make=([^\s&]+)&model=([^\s&]+)&year=([^\s&]+)\&mileage=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1/%2/%3? [R=302,L]

RewriteRule ^buy-car/([\w-]+)/([\w-]+)/([\^;a-zA-Z0-9_-]+)/([\^;a-zA-Z0-9_-]+)/?$ buy-car.php?make=$1&model=$2&year=$3&mileage=$4 [L,QSA,NC]


RewriteCond %{THE_REQUEST} /buy-car\.php\?make=([^\s&]+)&model=([^\s&]+)&year=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1/%2/%3? [R=302,L]

RewriteRule ^buy-car/([\w-]+)/([\w-]+)/([\^;a-zA-Z0-9_-]+)/?$ buy-car.php?make=$1&model=$2&year=$3 [L,QSA,NC]



RewriteCond %{THE_REQUEST} /buy-car\.php\?make=([^\s&]+)&model=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1/%2? [R=302,L]

RewriteRule ^buy-car/([\w-]+)/([\w-]+)/?$ buy-car.php?make=$1&model=$2 [L,QSA,NC]


RewriteCond %{THE_REQUEST} /buy-car\.php\?year=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1? [R=302,L]

RewriteRule ^buy-car/([\^;0-9-]+)/?$ buy-car.php?year=$1 [L,QSA,NC]


RewriteCond %{THE_REQUEST} /buy-car\.php\?make=([^\s&]+)\s [NC]
RewriteRule ^ buy-car/%1? [R=302,L]
RewriteRule ^buy-car/([\w-]+)/?$ buy-car.php?make=$1 [L,QSA,NC]

可能是什么解决方案。 感谢

1 个答案:

答案 0 :(得分:0)

我强烈建议使用前控制器.htaccess,而不是保留这么多规则,可能更多,因为可选的查询参数:

DirectryIndex index.php
RewriteEngine On
RewriteBase /

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) index.php?uri=$1 [L,QSA]

然后在php代码中使用$_GET['uri']来获取请求的URI并处理它们。