Httpd – Rewrite URLs in apache with & in the query

apache-2.2httpdmod-rewrite

I am trying to construct a rewrite condition and rule to rewrite URLs with & in the query string, rather than just &. This has occurred because of some invalid encoding when the URL is transmitted to a client in XML. Long term that will be fixed, but short term if I can put a rewrite rule in place it will stop 404 errors.

An example URL is

https://myserver.com/getpdf/download?md5=53d64aee8107d8f8af0c&id=163464591&tz=GMT

So far I have got this

RewriteCond %{REQUEST_URI} ^/getpdf/download*
RewriteRule ^/([^&]+)(&)(.*)$ /$1&$2 [N]

based on other posts on serverfault (eg mod-rewrite: Replacing some characters in a url)

I turned on the rewrite log and this is what I see

10.0.0.64 - - [12/Mar/2016:06:42:52 +0000] [myserver.com/sid#7f24e32103e8][rid#7f24e3379870/initial] (2) init rewrite engine with requested uri /getpdf/download
10.0.0.64 - - [12/Mar/2016:06:42:52 +0000] [myserver.com/sid#7f24e32103e8][rid#7f24e3379870/initial] (3) applying pattern '^(md5)([^&]+)(&)(.*)$' to uri '/getpdf/download'
10.0.0.64 - - [12/Mar/2016:06:42:52 +0000] [myserver.com/sid#7f24e32103e8][rid#7f24e3379870/initial] (1) pass through /getpdf/download

Any guidance on how to correctly form the rewriterule would be great.

Best Answer

Apache documentation states that if you want to rewrite query string part of the URI, then you need to use RewriteCond %{QUERY_STRING}.

So, you should try this:

RewriteCond %{QUERY_STRING} md5=([0-9a-f]{20}(&)(id=[0-9]+)(&)(.*)
RewriteRule ^md5=([0-9a-f]{20}(&)id=([0-9]+)(&)(.*)$ md5=$1&id=$2&$3 [N]