How to redirect URLs using the proxy module in Apache

apache-2.2http-proxyredirect

This seems like a super-basic question but I am having a hard time tracking down a straightforward solution, so appreciate any help and patience with me on this:

I want to configure my Apache proxy server to redirect certain URLs so that, for example, a web browser HTTP request for www.olddomain.com gets passed to the proxy server which then routes the request to www.newdomain.com which sends a response to the proxy server which then passes it back to the web browser.

Seems so simple, yet I don't see how to achieve this on Apache. I know Squid/Squirm offer this functionality so am guessing I am missing something really basic. I know I can use RewriteRule to dynamically modify the URL and pass it to the proxy server, but I effectively want to do the reverse, whereby the proxy server receives the original URL, applies the RewriteRule, and then forwards the HTTP request to the new URL.

Hope that makes sense. Thanks in advance for any help.

Best Answer

From your comment on my previous answer I gather that you are using Apache as a forwarding proxy (ProxyRequests On). You can use mod_rewrite to proxy pass through specific URL's.

You probably got something like this in your Apache config:

ProxyRequests On
ProxyVia On
<Proxy *>
   Order deny,allow
   Allow from xx.xx.xx.xx
</Proxy>

Then you have to add the following in order to proxy-pass all requests from www.olddomain.com/foo to www.newdomain.com/bar:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$
RewriteRule /foo(.*)$ http://www.newdomain.com/bar/$1 [P,L]

What this does is:

  • When a request is made to the host www.olddomain.com, the RewriteRule will fire.
  • This rule substitutes /foo to http://www.newdomain.com/bar/.
  • The substitution is handed over to mod_proxy (P).
  • Stop rewriting (L).

Example result:

  • Browser is configured to use your Apache as proxy server.
  • It requests www.olddomain.com/foo/test.html.
  • Your Apache will rewrite this to www.newdomain.com/bar/test.html.
  • It will request this page from the responsible web server.
  • Return the result to the browser as www.olddomain.com/foo/test.html.