Apache Reverse Proxy Example

The Simplest reverse proxy configuration possible is the code below, with this configuration your server will proxy all requests from example.com
to subdomain.example.com,

<VirtualHost *:80>
    ServerAdmin [email protected]
    ProxyRequests off
    ServerName example.com
    ProxyPreserveHost On
    <Location />
        ProxyPass http://subdomain.example.com/
        ProxyPassReverse http://subdomain.example.com/
        Order allow,deny
        Allow from all
    </Location>
 
</VirtualHost>


While the above example is simple and mostly just works™, there is a major downside, in that some applications (most?) insert the full URL of the assets on the web-app using this style of URLs

<img src='http://subdomain.example.com/img/example.jpg'>

instead of the relative and more portable URLs:

<img src='img/example.jpg'>

But with a little bit of fiddling, you can use apache with mod-substitute to rewrite the HTML file after it being processed by php,node,etc but before sending it to the client, the full configuration would look something like this:


<VirtualHost *:80>
    ServerAdmin [email protected]
    ProxyRequests off
    ServerName example.com
    ProxyPreserveHost On
    <Location />
        ProxyPass http://subdomain.example.com/
        ProxyPassReverse http://subdomain.example.com/
        SetOutputFilter INFLATE;SUBSTITUTE;DEFLATE
        AddOutputFilterByType SUBSTITUTE text/html
        Substitute "s|http://subdomain.example.com/||in"
        Order allow,deny
        Allow from all
    </Location>
 
</VirtualHost>

With the directive ‘Substitute’ from mod-substitute you can create really simple yet powerful rules to rewrite the HTML of a page, without having to change the source code of your application this way fixing a few pesky problems that plague everyone trying to make something work behind a reverse-proxy.

Sources:

https://httpd.apache.org/docs/2.4/mod_substitute.html

https://httpd.apache.org/docs/2.4/mod/mod_proxy.html

https://www.jamescoyle.net/how-to/116-simple-apache-reverse-proxy-example