简体   繁体   中英

URL rewrite for converting path to querystring

I try to make the URL like the following

http://domain/d1/d2/k1/val1/k2/val2/k3/val3 

To be

http://domain/index.php?one=d1&two=d2&k1=val1&k2=val2&k3=val3

Above one and two are fixed keys, the rest of the path is for key-value pairs. When I have more key-value pairs (more than three) attached after /d1/d2/, how do I write out the URL rewrite rules?

Update#1:

Below is what I have so far. I cannot have a dynamic key value pairs appended at the end of the first two folders.

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !\.(css|png|jpe?g|gif)$ [NC]
RewriteCond %{REQUEST_URI} !index\.php [NC]
RewriteRule  ^([^/]+)/([^/]+) /index.php?one=$1&two=$2 [QSA,L]

I was thinking to add one more folder "query" (see below) to help for pattern match for key-value pairs because you know after query all the folders are about key-value pairs. But, I cannot go further.

http://domain/d1/d2/query/k1/val1/k2/val2/k3/val3 

The trick is to loop through a rewrite rule until all elements of the directory are replaced. First change all the key/value pairs, then d1 and d2:

# Convert key/value pairs at end of line. Loop (N) until path is just two levels deep
RewriteCond %{REQUEST_URI} ^/(\w+)/(\w+)
RewriteRule (.+)/(\w+)/(\w+)$ $1?$2=$3 [QSA,N]

# Replace two final paths to query string and append to /index.php
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule /(\w+)/(\w+) /index.php?one=$1&two=$2 [QSA]

An alternative would be to redirect all requests at /index.php with the original path appended as the query string. You could then easily examine the elements of the original path using PHP instead.

See https://stackoverflow.com/a/8019730/1554386

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