Dynamic Reverse Proxy with Apache, mod_rewrite, and mod_proxy

Recently I found myself want­ing to expose more and more inter­nal web ser­vices to the out­side. We have an inter­nal mail caching server, ticket sys­tem, a hand­ful of devel­op­ment sites, as well as sev­eral other inter­nal web ser­vices that would be handy to access from remote loca­tions. If you have inter­nal dns, and your dns heirichy is sane you can prob­a­bly use the same trick I did to allow any inter­nal web­ser­vice that has a proper fqdn to work from out­side your local LAN. I used Apache2, mod_proxy, and mod_rewrite. Only a few lines need to be altered in the default apache site install.


You need to apti­tude install libapache2-mod-proxy-html apache2, and a2enmod proxy proxy_connect proxy_html proxy_http rewrite.

Then com­ment out the the line

Redi­rect­Match ^/$ /apache2-default/

from /etc/apache2/sites-available/000-default.

Then add these lines out­side a Direc­tory directive.


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

RewriteEngine on
RewriteRule ^(.+) $1 [P]
ProxyPassReverse / $1

Thats basi­cally it. So if you have a dns setup where something.lan.tld.com resolves to your main fire­wall from the out­side. But on the inside resolves to a local web­server, and you have defaulted port 80 to this new gate­way machine you should be able to access the inter­nal machine from outside.

The thing to note is that remotely something.lan.tld.com will resolve to your pub­lic ip. And locally it will resolve to a local lan ip. That allows the rewrite and proxy rule to work cor­rectly. Since it just rewrites the same thing and prox­ies for it the gate­way server has to be able to resolve the inter­nal names correctly.

Exam­ple:

ticket.lan.somecompany.com resolves to a world routable address like 151.164.1.8. (externally)

ticket.lan.somecompany.com resolves to a local ip like 192.168.1.5 (internally)

Now you can access that inter­nal resource with the same domain name either inter­nally or externally.

It scales well because you do not have to add a new proxy rule for each spe­cific inter­nal resource, all you have to do is add dns both exter­nally and inter­nally. On top of that you could wild­card your exter­nal dns for *.lan.somecompany.com and then all that has to be done is add inter­nal dns for each resource you want to access.

2 Comments

Leave a Reply

Your email is never shared.Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha