Apache rewrite request using a different proxy server

I would like to redirect the request in Apache based on the request header to another proxy. I think it is best to use mod_rewrite, but it can only use the reverse proxy defined in the same apache configuration.

I also checked the ProxyRemote property for mod_proxy, but cannot be used based on conditions, only based on url request.

I need something like:

If X-CUSTOM-HEADER is value-1 → request to forward proxy p1 If X-CUSTOM-HEADER is value-2 → request to forward proxy p2

and etc.

Dean, did anyone manage to do something like this?

Thanks Alin

+6
apache proxy mod-rewrite forward
source share
3 answers

I found a solution, it is not very elegant. It also requires some adaptation on the second server.

This comes from a project in which I had a similar problem, but in order for the servers to be "completely" (selected by a custom script that uses database resources).

This should at least work (I run my URL through a rewrite map to change it, I adapted it to use headers using RewriteCond ).

 # example for server number "5" in your remote proxy network RewriteCond %{HTTP:X-CUSTOM-HEADER} 1 RewriteRule http://([a-z0-9\.]+)/(.*) http://$1.5.server.yourdomain.com$1 [P] ProxyRemoteMatch .*\.5\.server\.yourdomain\.com.* http://5.server.yourdomain.com:80 

You basically adapt the URL so that it is a subdomain of your second server, and then you delete it again.
This part goes to the second (remote proxy):

 <ProxyMatch "http://.*\.[0-9]+\.server\.yourdomain\.com/.*"> RewriteEngine on RewriteRule (proxy:http[s]?://.+)\.[0-9]+\.server\.premiumize\.me(.+) $1$2 ... your code ... </ProxyMatch> 
+2
source share

Try the following:

 # Prevents Apache from functioning as a forward proxy server (where you don't want) ProxyRequests Off # Preserve Host in http protocol on destination server ProxyPreserveHost On <Proxy *> Order deny,allow Allow from all </Proxy> # enable rewrite engine RewriteEngine On # check header RewriteCond %{HTTP:X-CUSTOM-HEADER} 1 # execute forward proxy RewriteRule (.*) http://server1/$1 [P,L,QSA] # check header RewriteCond %{HTTP:X-CUSTOM-HEADER} 2 # execute forward proxy RewriteRule (.*) http://server2/$1 [P,L,QSA] 
+1
source share

you can achieve this by checking the RewriteCond directive with% {HTTP: header}.

Try the following:

 RewriteEngine On RewriteCond %{HTTP:X-CUSTOM-HEADER} 1 RewriteRule (.*) http://p1.example.com$1 [P] ProxyPassReverse / http://p1.example.com RewriteCond %{HTTP:X-CUSTOM-HEADER} 2 RewriteRule (.*) http://p2.example.com$1 [P] ProxyPassReverse / http://p2.example.com 

Hope this helps. :)

0
source share

All Articles