Proxy Node.js using Apache


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>

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

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

	SSLProxyEngine On
	SSLEngine On 
	SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
	SSLHonorCipherOrder On 
	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

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

<VirtualHost *:80>

        RewriteEngine On
        RewriteRule ^/(.*)$$1 [R,L]

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...