开发者

use mod_rewrite to catch all querystring vars

I was wondering if anyone has any decent references for mod_rewrite?

Ive been scouring the web and found a few cheat sheets for it and managed to come up with

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

which works ok if all the 4 varibles are present. However I want to be able to pass different amounts at once.

e.g. cat/1 cat/1/item/2 cat/1/sort/asc cat/1/sort/dec/filter/type

开发者_运维知识库what ive done allows me to have them in what ever order, which is fine - however if they are not all present it dies.

is it possible for it to have as many or few items as needed?

cheers in advance

Fred


As suggested by @Pekka - if you are not sure of the number of variables which you will be handling in this manner, then trying to capture each of them with a long drawn-out mod_rewrite argument is not going to work.

In your .htaccess file

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]

In your index.php file

<?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 );
}
?>

Using that code, calling a URI of "http://www.server.com/search/a/apple/b/banana" will, when parsed by the above PHP generate an array $route with a value of array( 'a' => 'apple' , 'b' => 'banana' );


You can define your own rewrite map that does that for you in an simple external program. This teqnique is very efficient because your script will be started only once and kept open. (it changes one line of stdin for one line of stdout). So the interpreter etc has not to be loaded.

However imo it would be a lot more elegant to do the logic in your application. In fact this is what almost all frameworks do.

Just do a rewrite rule that rewrites everything to your bootstrap fileand there you can deal with the whole thing. It will be a lot easier to maintain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜