Apache 2.4 – double encode already encoded query string in URL

apache-2.4mod-rewrite

I need help regarding a requirement. We have Apache 2.4.6 installed

I have a URL which has an encoded query string:

https://example.com/home?testStr%3Dhello%26id%3Drad

I am trying to find out how to double encode only the query string part of the URL using mod_rewrite in Apache webserver to:

https://example.com/home?testStr%253Dhello%2526id%253Drad

This is for one of the issues I am trying to fix.

Best Answer

Just to echo the concerns in comments... this is a strange requirement. However, you can do this using mod_rewrite. For example, try the following:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^(testStr%3Dhello%26id%3Drad)$
RewriteRule ^/?(home)$ /$1?%1 [B,NE,R,L]

This issues a temporary (302) redirect from /home?testStr%3Dhello%26id%3Drad to /home?testStr%253Dhello%2526id%253Drad (doubly encoded).

The QUERY_STRING server variable is not %-decoded, so you match against the literal query string as given in the RewriteCond directive.

The $1 backreference refers to the captured subpattern in the RewriteRule pattern ie. home.

The %1 backreference refers to the captured subpattern in the last matched CondPattern (the RewriteCond directive) ie. the %-encoded query string (testStr%3Dhello%26id%3Drad).

The B (escape backreferences) flag on the RewriteRule directive %-encodes the backreference (%1) to effectively doubly-encode the query string.

The NE (noescape) flag prevents the susbstitution being further (triple) URL-encoded!