Serving web applications with Apache

Serving web applications with Apache

Let's imagine we have a server with Apache2 listening on port 80. Since port 80 is used, other web apps, developed for example with Node.js, must use another port. Consequently, one would need to open a new port on one's router every time a new app is developed.

To solve this problem, Apache can be set to redirect requests to other destinations than itself. In other words, Apache serves as a reverse proxy.

This is achieved using the proxy module.

Here is an example configuration file that listens to HTTPS requests for myapp.mydomain.com and redirects them to port 8080 of the same machine (localhost). Additionally, it enforces HTTPS by redirecting HTTP requests to its HTTPS counterpart.

<VirtualHost *:80>
    # Redirection through HTTPS
    ServerName myapp.mydomain.com
    Redirect / https://myapp.mydomain.com
</VirtualHost>
    
<IfModule mod_ssl.c>
    <VirtualHost :443>
    
        ServerName myapp.mydomain.com
        
        # SSL configuration
        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/myapp.mydomain.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/myapp.mydomain.com/privkey.pem
        
        # Proxy config
        SSLProxyEngine On
        ProxyRequests Off
        ProxyPreserveHost On
        ProxyVia Full
        
        <Proxy >
                Require all granted
                Allow from all
                Order deny,allow
        </Proxy>
        
        ProxyPass / http://localhost:8080/
        ProxyPassReverse / http://localhost:8080/
    
    </VirtualHost>
</IfModule>