Reference capture groups of multiple RewriteCond in RewriteRule

后端 未结 2 339
你的背包
你的背包 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:05

    You could try constructing the target URL inside the rewrite conditions:

    RewriteCond ##%{QUERY_STRING}      (.*)##(|.*&)param1=([^&]+)
    RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param2=([^&]+)
    RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param3=([^&]+)
    RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param4=([^&]+)
    RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param5=([^&]+)
    RewriteCond %1/%3##%{QUERY_STRING} (.*)##(|.*&)param6=([^&]+)
    
    RewriteRule ^foo$ /bar%1/%3? [L,R]
    

    When I try to request:

    /foo?param1=a&param2=b&param6=3&param3=4&param5=5&param4=6

    I get redirected to:

    /bar/a/b/4/6/5/3

    Adding any additional required query string parameters won't make it look any more messy than it already is.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题