Multiple Web Servers over a Single IP, Using Apache as a Reverse Proxy

As a developer, I don’t get to play with the IT side of things quite as much as I would like to.  So I enjoy the little things, like learning how to use a reverse proxy on Apache.  At home, I only have one IP coming in with my regular Internet connection, and I want the ability to run multiple servers inside my network on port 80. In the past, I’ve always just setup a new port and routed it to whichever server I wanted. 8080 here, 8081 there, etc. Well with Apache reverse proxy (mod_proxy), I found it was very easy to setup route requests to other internal servers.

reverse_proxy

This diagram shows the basic idea of what I’m doing.  I have a “landing” server that takes all the traffic from the router. Using virtual hosts, I filter the web traffic by hostname and then provide mod_proxy directives to hand off the requests to other internal web servers.  Options like ProxyPreserveHost allow you to hand off the original hostname in the request so you can further use hostname filtering on the secondary servers.

Here is an example of the landing server configuration.

NameVirtualHost *:80

<VirtualHost *:80>
  ServerName foo.com

  DocumentRoot /srv/www/default

  <Location "/">
    Order Deny, Allow
    Deny from all
    Allow from all
  </Location>
</VirtualHost>

<VirtualHost *:80>
  ServerName fooa.com

  ProxyPreserveHost on
  ProxyPass / http://server2/
  ProxyPassReverse / http://server2/
</VirtualHost>

<VirtualHost *:80>
  ServerName foob.com
  ServerAlias fooc.com

  ProxyPreserveHost on
  ProxyPass / http://server3/
  ProxyPassReverse / http://server3/
</VirtualHost>

You can see here, that the default site [foo.com] actually his hosted by the landing server. The rest of the hostnames are passed on to the other internal servers.  You can also proxy just virtual directories as well. So if you want the requested path, “/something-foo” to go to another internal server, you can. You just use /something-foo as the first argument in ProxyPass and ProxyPassReverse.

The other web servers would have normal configurations like this one below. You can also proxy requests to other web servers like IIS. The proxy will handle basic authentication with an internal Windows IIS server.

NameVirtualHost *:80

<VirtualHost *:80>
  ServerName fooa.com

  DocumentRoot /srv/www/fooa.com

  <Location "/">
    Order Deny, Allow
    Deny from all
    Allow from all
  </Location>
</VirtualHost>

That’s it!