Using mod_rewrite with Multiple Query Strings in Apache 2.4

.htaccessapache-2.4mod-rewriteregex

This is an extension to my question https://serverfault.com/a/761474/77231

I am trying to add an additional QUERY STRING parameter to the URL and change spaces to underscores but am having no success.

Instead of simply changing:

http://somedomainname.com/grafana/dashboard/db/generic-ping?var-device=SF-some.machinename.com

to:

http://somedomainname.com/grafana/dashboard/db/generic-ping?var-device=SF-some_machinename_com

I'm trying to change an additional parameter like:

http://somedomainname.com/grafana/dashboard/db/generic-check?var-device=SF-some.machinename.com&var-check=Check CPU Load

to:

http://somedomainname.com/grafana/dashboard/db/generic-check?var-device=SF-some_machinename_com&var-check=Check_CPU_Load

Using the same logic in my previously answered question, I'm able to get the first part working using:

RewriteCond %{QUERY_STRING} (.*)\.(.*)\.(.*)
RewriteRule ^/grafana/dashboard/db/generic-check /grafana/dashboard/db/generic-check?%1_%2_%3 [R=301]

But that only obviously gets me the first part and comes out like:

http://somedomainname.com/grafana/dashboard/db/generic-check?var-device=SF-some_computername_com&var-check=Check%2520CPU%2520Load

I've added an additional QUERY_STRING and rewrite rule like:

RewriteCond %{QUERY_STRING} ^&var-check=(.*)\ (.*)\ (.*)
RewriteRule ^&var-check var-check=%1_%2_%3 [R=301]

…without success.

I've also tried combining the two:

RewriteCond %{QUERY_STRING} (.*)\.(.*)\.(.*)&(.*)\ (.*)\ (.*)
RewriteRule ^/grafana/dashboard/db/generic-check /grafana/dashboard/db/generic-check?%1_%2_%3&%4_%5_%6 [R=301]

..also without success, as well as using %20 \s and %2520 instead of \ and a space… as well as all with a pipe separator like \ |\s|%20|%2520.

Ideally I'd like this work in one rewrite, but I'd be happy to just have it work. Any help is appreciated.

Best Answer

I was able to get this by adding the following condition and rule.

RewriteCond %{QUERY_STRING} ^(.*)(%2520)(.*)(%2520)(.*)$
RewriteRule ^(.+)$ $1?%1_%3_%5 [R=301]

Unfortunately, I need to repeat this cond/rule for however many spaces may come up. I tried a bunch of different conditions and rules [N] didn't seem to ever do what it was supposed to do.

I'm still open for answers as I feel this can be done better, more reliably, and/or more robust.

Related Topic