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


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

2 Answers 2


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]
  • Tero, thanks for your pointers. The answer needed some more tweaking, I'm going to post the solution now.
    – gingerkid
    Mar 14, 2016 at 13:47

With the help of Teros answer pointing me in the right direction I solved my rewrite rule.

First step was to match against %{QUERY_STRING}.

RewriteCond %{QUERY_STRING} ^md5=([0-9a-f])(&)id=([0-9])(&)(.*)$

And the second step was to rewrite the entire URL. My mistake was in thinking that I could modify only the query string.

RewriteRule ^(.*)$ https://myserver.com/getpdf/download?md5=%1&id=%3&%5 [N]

Some tips

  • %1 in the RewriteRule uses groups from the RewriteCond
  • $1 would use groups from the regex in the RewriteRule instead
  • Rewrite uses Perl Compatible Regular Expressions (PCRE). I used this tester to check my regex - https://regex101.com/#pcre
  • Google "Learn Apache mod_rewrite: 13 Real-world Examples"
  • The apache intro to rewrite, and the image showing the basics, helps - https://httpd.apache.org/docs/2.4/en/rewrite/intro.html (essentially a case of RTFM :) )

Hope this helps others lost in the world of rewrite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.