Reference capture groups of multiple RewriteCond in RewriteRule

后端 未结 2 348
你的背包
你的背包 2020-12-03 05:42

When I have multiple RewriteCond chained together, only the capture groups of the last RewriteCond can be referenced with %0-%9.

In the fol

2条回答
  •  爱一瞬间的悲伤
    2020-12-03 06:18

    After experimenting some more, it would be possible to parse all parameters as environment variables and use them like that. I doubt it is very efficient though and I think any use-case that would need such a construction would be better of using a php page router. For fancy url's Jon Lin's solution would probably work better. It does however sort-of mimic what I had in mind.

    I'll, however, put the code in here for demonstration:

    #Parse all query key-value pairs to an environment variable with the q- prefix
    RewriteCond %{QUERY_STRING} ^([^=]*)=([^&]*)(&(.*)|$)$
    RewriteRule ^(.*)$ $1?%4 [E=q-%1:%2,N]
    
    #If 'param1' existed in the query string...
    RewriteCond %{ENV:q-param1} !^$
    RewriteRule ^foo$ bar/%{ENV:q-param1} [END]
    

    or even...

    #Keep the original query string
    RewriteCond %{ENV:qstring} ^$
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule .* - [E=qstring:#%1]
    
    #parse the query parameters to environment variables
    RewriteCond %{ENV:qstring} ^#([^=]*)=([^&]*)(&(.*)|$)$
    RewriteRule ^(.*)$ - [E=q-%1:%2,E=qstring:#%4,N]
    
    #See that the original query string is still intact
    RewriteCond %{ENV:q-param1} !^$
    RewriteRule ^foo$ bar/%{ENV:q-param1} [QSA]
    

提交回复
热议问题