.htaccess rewrite to convert directories into /key/value/key/value

僤鯓⒐⒋嵵緔 提交于 2020-01-20 06:53:35

问题


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.


回答1:


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.




回答2:


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.




回答3:


You have an excellent tutorial here

http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/



来源:https://stackoverflow.com/questions/8794441/htaccess-rewrite-to-convert-directories-into-key-value-key-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!