How to read POST parameters, cookies or HTTP headers using Apache mod_rewrite

2.1k views Asked by At

I have an application running under Tomcat 6. In front of it I have an Apache server which is forwarding all requests. That is, the user "talks" to Apache and not to Tomcat. For some reason the Apache server receives a request to the URL:

http://www.example.com/myApp

then it has to be forwarded to http://www.example.com/$PREFIX/myApp

where $PREFIX is a POST parameter. This $PREFIX parameter is also available as a COOKIE and as an extra header.

I couldn't find a way using mod_rewrite to read POST parameters/cookies/headers.

Is this possible at all? If not, should I use another Apache module/connector?

3

There are 3 answers

1
Fenton On

You can't use POST data for mod_rewrite. This is because the POST data isn't in the HEADER of the http request, it's in the BODY.

My suggestion would be that you perform an action on the posting page that adds the prefix to the URL, which would mean you don't even need to rewrite.

1
SeriousCallersOnly On

try something like (my regex is a bit flakey so may need a bit of tinkering):

RewriteCond %{HTTP_COOKIE} yourcookie=(.*)
RewriteRule ^/myApp(.*)$ /%1/$1 [R,L]

The %1 will backreference to groups in the RewriteCond pattern.

More examples here

0
MrWhite On

As already mentioned, you can't read the POST body using mod_rewrite. However, you can read the Cookie header (using the HTTP_COOKIE server variable) and any other custom HTTP request header.

If the information you require is available in a custom header then it's probably easier/safer to read that since the HTTP_COOKIE contains all the cookie name/value pairs sent from the client so you must be particular in extracting the required information.

If the required information is always contained in the X-Prefix HTTP request header then you can internally rewrite the request with a single mod_rewrite directive:

RewriteRule ^/?(myApp)$ /%{HTTP:X-Prefix}/$1 [L]

The $1 backreference simply saves having to repeat the myApp string in the substitution from the requested URL-path.

If you want to first check that the HTTP request header is set before rewriting then you can use an additional condition:

RewriteCond %{HTTP:X-Prefix} (.+)
RewriteRule ^/?(myApp)$ /%1/$1 [L]

In the second rule block, the request is only rewritten if the X-Prefix header is set and has a value. This is captured using the %1 backreference, rather than referring to the custom HTTP directly in the substitution string (which we could do, but just saves repetition).