Search code examples
.htaccessmod-rewriteurl-rewriting

htaccess - map all query parameters to a simple path/URI without params -- RewriteCond / RewriteRule / mod_rewrite


I'd like htaccess to take

image.svg?a=1&b=2

And map it to

image--a-1--b-2.svg

Where a and b could be any variable, and there could be more parameters too, eg. a, b and c etc.

This very simplistic example would work for one parameter, but not multiple/dynamic:

RewriteCond %{QUERY_STRING} a=(.*)
RewriteRule ^image.svg$  /image--a-%1.svg?

Solution

  • RewriteCond %{QUERY_STRING} ([^=]+)=([^&]*)&*(.*)
    RewriteRule ^(.*)\.svg$  $1--%1-%2.svg?%3 [NC,L]
    

    This solution uses the fact, that rewrite will restart its filter work, when a change has occured, so cycling through all key=value pairs.

    We

    1. separate the (1)key (2)value (3)'rest of QUERY_STRING'
    2. prepare the new REQUEST_URI with the extended file name $1--%1-%2.svg and concatenate with ? the shortened QUERY_STRING %3 that contains the remaining attributes.
    3. [L]Leave (and so restart) rewrite, to grab the next set from the QUERY_STRING

    The last cycle will leave an empty QUERY_STRING, dropping the final ?. As the QUERY_STRING is empty the loop ends.