Apache rewriteRule: add target URL parameter with query string

apache-2.2mod-rewrite

I'm trying to pass my original URL as a query string for a servlet controller using a TARGET_URL parameter. Is it possible to do a URLencode for the TARGET_URL?

Here is an example:
Orginal: http://myhost.com/app1/navigationControler?page=2&u=0
would become: http://myhost.com/app2/controller?TARGET_URL=http%3a%2f%2fmyhost.com%2fapp1%2fnavigationControler%3fpage%3d2%26u%3d0

Best Answer

Yes, it is possible using mod_rewrite and an 'escape' rewrite map. See http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritemap

First, you need to define the rewrite map in your server or virtual host config, like this:

RewriteMap escaped int:escape

This creates a rewrite map named "escaped" that will translate special chars in the string to their hex encodings. You can use it like this ${escaped:text to escape}.

Next, you need to work up an appropriate set of rewrite rules to pass the information to your handler:

RewriteRule .* - [E=HT:http]
RewriteCond %{HTTPS} =on
RewriteRule .* -  [E=HT:https]
RewriteRule .* %{ENV:HT}://myhost.com/app2/controller/?TARGET_URL=${escaped:%{ENV:HT}://%{HTTP_HOST}%{REQUEST_URI}?%{QUERY_STRING}}

The first three lines figure out whether you should use 'http' or 'https' in your final rewrite. The last line makes a go at putting the original URL through the escape rewrite map and sending it along to your servlet/handler.

This is a little complicated, since it tries to handle http and https. One problem is that it will always include the ? char, even if the original request does not have a query string.

The last comment I have would be to suggest that you think about just proxying or using AJP to your servlet controller, which would make all this URL parameter manipulation unnecessary.