2

I am trying to build a reverse proxy using Apache. My goal is to proxy all requests of the form <subdomain>.domain.com/file.html to www.domain.com/<subdomain>/file.html.

I somehow need to capture the <subdomain> of the original URL and use it to construct the target URL.

I assume that I need an Apache directive that can match regular expressions on the whole URL, instead of the part of the url after %{HTTP_HOST}, since my target URL contains the original URL's subdomain. For this reason I can't use the ProxyPassMatch directive, since it only matches the part of the URL after %{HTTP_HOST}.

Another alternative is to use as many VirtualHost sections as my subdomains. But of course this solution doesn't make sense, since my subdomains will keep increasing.

Any tips on how to tackle this?

1 Answers1

1

Ok, I managed to solve it using Rewrite rules.

# Requires Apache module ``proxy_http``, ``rewrite``
<VirtualHost *:80>
    ServerName primary.domain.com
    ServerAlias *.domain.com

    ProxyRequests Off
    <Proxy *>
         Order deny,allow
         Allow from all
    </Proxy>

    RewriteEngine On

    RewriteCond %{HTTP_HOST}/%{REQUEST_URI} ^(.*)\.domain\.com/(.*)$
    RewriteRule (.*)    http://www.domain.com/%1%2 [P]

 </VirtualHost>

Basically what happens is this:

  • RewriteCond matches all incoming requests whose URL matches .domain.com/
  • RewriteRule proxies the request to the URL http://www.domain.com/%1/%2, where %1 and %2 are the subdomain and request uri of the original request, respectively.
  • 1
    You got it. You got RewriteCond, and you got % (rather than $) which is a little obscure, but as far as I know necessary to this particular problem. (Aren't you missing a slash?) – Chuck Kollars Oct 01 '12 at 03:45
  • @ChuckKollars: Do you mean about a slash between ``%1`` and ``%2``, in the ``RewriteRule``? The Request Uri (``%2``) already includes the slash, so it's not needed. In my explanation I included it though to make it more explicit. – Charalambos Paschalides Oct 01 '12 at 09:28