Proxy Node.js using Apache

Cables

One of the best ways to serve a Node web service is to reverse proxy it through Apache. A reverse proxy accepts inbound requests from clients and passes those requests back to the origin server (your application).

When setting up any HTTP based service it is highly recommended to use SSL (HTTPS) in all cases. Using a free certificate authority like Let’s Encrypt makes this easy and really leaves no excuse for not doing so.

A virtual host can easily be configured to proxy requests for your Node web service application. Change the port number to suit your own settings.

<VirtualHost *:443>
	ServerName mynodeapp.com
	ServerAlias www.mynodeapp.com

	ErrorLog /var/www/mynodeapp/logs/error.log
	CustomLog /var/www/mynodeapp/logs/access.log combined

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

	SSLProxyEngine On
	SSLEngine On 
	SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
	SSLHonorCipherOrder On 
	SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
	SSLCertificateFile /etc/letsencrypt/live/mydomain/cert.pem
	SSLCertificateKeyFile /etc/letsencrypt/live/mydomain/privkey.pem
	SSLCertificateChainFile /etc/letsencrypt/live/mydomain/chain.pem

	ProxyPreserveHost On
	ProxyPass / http://localhost:3000/
	ProxyPassReverse / http://localhost:3000/

	<Location />
		Order allow,deny
		Allow from all
	</Location>
</VirtualHost>

And of course we want to direct any requests via plain HTTP to HTTPS:

<VirtualHost *:80>
        ServerName mynodeapp.com
        ServerAlias www.mynodeapp.com

        RewriteEngine On
        RewriteRule ^/(.*)$ https://mynodeapp.com/$1 [R,L]
</VirtualHost>

Sometimes you may want to use the default error pages or redirect to custom ones. This can be achieved by using the ProxyErrorOverride directive.

ProxyErrorOverride On

You can also prevent certain response codes from being included by using the ProxyPass directive.

ProxyPass /400.html !
ProxyPass /404.html !

You may also like...