开发者

Apache URL Rewriting with n arguments

开发者 https://www.devze.com 2022-12-20 05:10 出处:网络
I\'m doing some URL rewriting and I can accomplish what I need to do with the following: RewriteRule ^([^/]*)/([^/]*)$ index.php?arg1=$1&arg2=$2 [L,QSA]

I'm doing some URL rewriting and I can accomplish what I need to do with the following:

RewriteRule ^([^/]*)/([^/]*)$ index.php?arg1=$1&arg2=$2 [L,QSA]
RewriteRule ^([^/]*)$ index.php?arg1=$1 [L,QSA]

You get what I'm trying to do here, I basically want to take the full url and parse it into individual arguments. So /blah/test/asdf/hi would come in as arg1=blah, arg2=test, etc.

Now, if I want to expand this to 4 or 5 arguments, I'm wondering if there's a cleaner way to pr开发者_运维问答esent it rather than going out with ?arg1=$1&arg2=$2&arg3=$3 etc. etc. I've seen people do this programatically (just take whole string with slashes and parse it in code) but I was curious if there was a way to do it with apache.


You can use PHP to do that:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$pathSegments = array_map('rawurldecode', explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1)));

The first line is to get just the URL path from the request URL. The other line will remove the leading slash (substr), split into the segments (explode) and decode each segment (array_map with rawrurldecode).

Now you just need to pass all request to your index.php:

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

The additional condition will exclude requests that can be mapped to existing files.

0

精彩评论

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

关注公众号