简体   繁体   中英

mod_rewrite: Convert 'Folders' in URL Into Query Parameters

I want to be able to take a URL like:

http://www.example.com/valOne/valTwo/valThree/valFour/valFive

and convert it to:

http://www.example.com/index.php?one=valOne&two=valTwo&three=valThree&four=valFour&five=valFive

I really only need a few query parameters for my application so the Regular Expression could have these five hard coded, but it would be nice if it could dynamically create new query parameters as additional 'folders' are added to the URL. Additionally, not all five folders or QPs will always be present, so it must be able handle that appropriately.

Here's a mod_rewrite rule that meets your needs:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?$ index.php?one=$1&two=$2&three=$3&four=$4&five=$5

But it would be certainly easier if you parse the requested URI path with PHP instead:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php

$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM