.htaccess:
RewriteEngine on
# skip rewriting if file/dir exists (optionally)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# rewrite all to results.php
RewriteRule . results.php
php(key => valueペアを使用した簡単な方法):
// current URI (/jobs/find/keyword/accounting-finance/state/NSW/type/free-jobs/page/1/?order=1)
$path = $_SERVER['REQUEST_URI'];
// remove base path (/jobs)
if (($len = strlen(basename($_SERVER['SCRIPT_FILENAME']))))
$path = substr($len, $path);
// remove GET params (?order=1)
if (false !== ($pos = strpos($path, '?')))
$path = substr($path, 0, $pos);
$path = explode('/', trim($path, '/'));
// extract action (or whatever 'find' is)
$action = array_shift($path);
// make key => value pairs from the rest
$params = array();
for ($i = 1, $c = count($path) ; $i < $c ; $i += 2) {
$params[urldecode($path[$i - 1])] = urldecode($params[$i]);
// or put it to GET (only remember that it will overwrite already existing values)
//$_GET[urldecode($path[$i - 1])] = urldecode($params[$i]);
}
このスクリプトを変更して、キーなしでのみ値を達成することができますが、ここで問題が発生します-値が1つのキーであるか別のキーであるかを判断することは可能ですか?パラメータが常に同じ位置にあり、取得できるパラメータが少ないか多い場合は、非常に簡単です。
// skip this step from previous example
//$action = array_shift($path);
$params = array(
'action' => null,
'keyword' => null,
'state' => null,
'type' => null,
'page' => null,
);
$keys = array_keys($params);
for ($i = 0 , $c = min(count($path), count($keys) ; $i < $c ; ++$i) {
$params[$keys[$i]] = urldecode($path[$i]);
}
しかし、どのパラメータがどの位置にあるかわからない場合は、事態はさらに複雑になります。すべてのパラメータに対していくつかのチェックを行い、それがどれであるかを判断する必要があります。これらの値のすべてが既知の値のリストから選択されている場合、たとえば、次のようになります。
$params = array(
'action' => null,
'keyword' => null,
'state' => null,
'type' => null,
'page' => null,
);
$params['action'] = array_shift($path);
$keys = array_keys($params);
foreach ($path as $value) {
if (is_numeric($value)) $params['page'] = intVal($value);
else {
$key = null;
// that switch is not very nice - because of hardcode
// but is much faster than using 'in_array' or something similar
// anyway it can be done in many many ways
switch ($value) {
case 'accounting-finance' :
case 'keyword2' :
case 'keyword3' :
$key = 'keyword';
break;
case 'NSW' :
case 'state2' :
$key = 'state';
break;
case 'type1' :
case 'type2' :
case 'type3' :
$key = 'type';
break;
// and so on...
}
if ($key === null) throw new Exception('Unknown value!');
$params[$key] = $value;
}
}
.htaccessにいくつかの非常に複雑な正規表現を書いてみることもできますが、IMOはそのための場所ではありません-apacheは、アプリケーション内の正しいエンドポイントとリクエストを一致させて実行する必要があります。拡張パラメータロジックの場所ではありません(とにかくそうなる場合)アプリ内の同じ場所に移動します)。また、そのロジックをアプリに保持する方がはるかに便利です-何かを変更するときは、htaccessまたはapache configで何も変更せずにアプリコードでそれを行うことができます(実稼働環境では、ほとんどの場合、.htaccessコンテンツをapacheconfigに移動しています.htaccessサポートをオフにします。これにより、apacheがこれらのファイルを検索していない場合に速度が向上しますが、変更を加えるにはapacheを再起動する必要があります)。