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

谁都会走 提交于 2019-12-11 07:33:40

问题


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?


回答1:


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.




回答2:


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




回答3:


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).



来源:https://stackoverflow.com/questions/1629581/how-to-read-post-parameters-cookies-or-http-headers-using-apache-mod-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!