Mod-Rewrite - 使用混合url结构

时间:2013-11-28 20:22:41

标签: regex .htaccess mod-rewrite

我需要重写网址,但没有确切的顺序。

例如,我需要能够:

www.domain.com/sale
www.domain.com/sale/new-york
www.domain.com/sale/offices
www.domain.com/sale/chicago/villas
www.domain.com/new-york
www.domain.com/washington/offices

等等。最后,它必须是:

file.php?type=sale
file.php?type=sale&city=new-york
file.php?type=sale&category=offices
file.php?type=sale&city=chicago&category=villas
file.php?city=new-york
file.php?city=washington&category=offices

所以主要的想法是我没有特定的子文件夹顺序,我可以使用它来构建通用规则。

我发现这个问题的唯一解决方案是自动生成的.htaccess,其中包括所有可能的情况和请求的变体(假设类别名称永远不会与城市名称和/或类型相同)。< / p>

还有其他可能通过正则表达式实现这一目标吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

我建议你在/.htaccess中测试一下:

RewriteEngine On
RewriteRule \b(sale)\b /file.php?%{QUERY_STRING}&type=$1
RewriteRule \b(chigaco|new-york|washington)\b /file.php?%{QUERY_STRING}&city=$1
RewriteRule \b(villas|offices)\b /file.php?%{QUERY_STRING}&category=$1

我们使用:

\bsale\b: sale is a whole word delimited by word boundary.
\b(chigaco|new-york|washington)\b: cities names must be known.
\b(villas|offices)\b: category names must be predictable.

我用这个/file.php进行了测试:

This is file.php
<?php
echo "<pre>";
var_dump($_GET);
echo "</pre>";
?>

它重写http://www.example.com/sale/new-york/villas,file.php输出此内容:

This is file.php
array(3) {
  ["type"]=>
  string(4) "sale"
  ["city"]=>
  string(8) "new-york"
  ["category"]=>
  string(6) "villas"
}

如果要处理所有世界城市,必须进行权衡,城市的前缀为:

RewriteEngine On
RewriteRule \b(sale)\b /file.php?%{QUERY_STRING}&type=$1
RewriteRule \b(villas|offices)\b /file.php?%{QUERY_STRING}&category=$1
RewriteRule \bcity-([\w-]+)\b /file.php?%{QUERY_STRING}&city=$1

即,您必须在HTML文档中使用这样的URL:

http://www.example.com/sale/city-new-york/villas
http://www.example.com/sale/city-beijing/offices
http://www.example.com/sale/villas/city-berlin
相关问题