.htaccess rewrite to convert directories into /key

2019-01-26 18:38发布

I've seen it before where a rule was used to convert directories on a URL to key=value request queries.

I have no idea how to do this so I can have more than one of these pairs.

For example:

http://www.example.com/mykey/myvalue/mykey2/myvalue2

Would map to:

http://www.example.com?mykey=myvalue&mykey2=myvalue2

Thanks.

标签: .htaccess url
3条回答
再贱就再见
3楼-- · 2019-01-26 19:17

Use this .htaccess code to have recursion based translation of key/value based URI:

Options +FollowSymLinks -MultiViews
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)(/.*)?$ $3?$1=$2 [N,QSA]
RewriteRule ^(/[^/]+|[^/]+/|/?)$ /index.php [L,QSA]

Using these rules a URL of http://localhost/n1/v1/n2/v2/n3/v3/n4/v4 will be INTERNALLY redirected to http://localhost/?n4=v4&n3=v3&n2=v2&n1=v1 treating each pair of URL segments separated by / as a name-value pair for QUERY_STRING. BUT keep in mind if URI doesn't have even number of segments eg: http://localhost/n1/v1/n2/ then it will be redirected to http://localhost/?n1=v1, discarding extra n2.

查看更多
狗以群分
4楼-- · 2019-01-26 19:35

The most common usage I've seen of this type of pattern is in the Zend Framework, but I believe this is achieved by the Front Controller, i.e. PHP code. There is, I believe, no way to match an unknown number of matches via mod_rewrite. That is to say, if you know there's going to be a maximum of say 3 pairs, you can use...

RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?$1=$2 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ /index.php?$1=$2&$3=$4 [QSA,L]
RewriteRule ([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ /index.php?$1=$2&$3=$4&$5=$6 [QSA,L]

...but if there is no known maximum it can't be done.

查看更多
登录 后发表回答