使用mod_rewrite来捕获所有查询字符串变量

时间:2011-03-11 11:43:23

标签: php mod-rewrite

我想知道是否有人对mod_rewrite有任何不错的引用?

我一直在网上搜索并找到了一些备忘单,并设法提出

Options +FollowSymLinks
RewriteEngine on
RewriteRule search/(.*)/(.*)/?(.*)/(.*)/?(.*)/(.*)/?(.*)/(.*)/?(.*)/(.*)/$ /search.php?$1=$2&$3=$4&$5=$6&$7=$8

如果所有4个变量都存在则可以正常工作。但是我希望能够一次传递不同的金额。

e.g。 猫/ 1 猫/ 1 /项目/ 2 猫/ 1 /排序/ ASC 猫/ 1 /排序/ DEC /滤波器/类型

我所做的事情让我可以将它们放在任何订单中,这很好 - 但是如果它们不是全部存在它就会死亡。

是否有可能根据需要包含多少项?

提前欢呼

佛瑞德

2 个答案:

答案 0 :(得分:2)

正如@Pekka所建议的那样 - 如果你不确定你将以这种方式处理的变量的数量,那么尝试使用长抽出的mod_rewrite参数来捕获每个变量都不会起作用。< / p>

.htaccess 文件

RewriteEngine On
RewriteCond %{REQUEST_URI} !-f # If the requested URI is NOT an existing file
RewriteCond %{REQUEST_URI} !-d # If the requested URI is NOT an existing folder
RewriteCond %{REQUEST_URI} ^/search/ # If the requested URI starts with "/search/"
RewriteRule /search/(.*) index.php?_route=$1 [QSA]

index.php 文件

<?php

# Initialise the Array
$route = array();

# Extract the $_GET['_route'] variable and parse it.
if( isset( $_GET['_route'] ) ){
 # The parameter exists
 # Create a Temporary Array
  $routeBitsRaw = array();
 # Break the string into an array at the "/" characters
  $routeBitsRaw = explode( '/' , $_GET['_route'] );
 # Loop through that array
  for( $i=0 , $c=count( $routeBitsRaw ) ; $i<=$c ; $i+2 ){
   # Create an Array element using a pair of Raw Array elements
   #  as the key and value respectively.
    $route[$routeBitsRaw[$i]] = $routeBitsRaw[$i+1];
  }
 # Destory the Temporary Array
  unset( $routeBitsRaw );
}
?>

使用该代码,调用URI“http://www.server.com/search/a/apple/b/banana”将在上述PHP解析时生成一个数组$route价值array( 'a' => 'apple' , 'b' => 'banana' );

答案 1 :(得分:0)

您可以在简单的外部程序中定义自己的rewrite map。这个teqnique非常有效,因为您的脚本只会启动一次并保持打开状态。 (它改变一行标准输出的一行标准输出)。 所以解释器等没有被加载。

然而,在您的应用程序中执行逻辑会更加优雅。事实上,这就是几乎所有框架所做的事情。

只需执行重写规则,将所有内容重写到引导程序文件中,然后就可以处理整个事情。维护起来会容易得多。