Simple Apache reverse proxy example
Category : How-to
Background
Apache can be used as a reverse proxy to relay HTTP/ HTTPS requests to other machines. This is common practice and comes with two main benefits:
- Security – Your Apache instance can be put in a DMZ and exposed to the world while the web servers can sit behind it with no access to the outside world.
- Reduce load – You can reduce the load on the web servers with various methods such as web caching at the proxy, load balancing and deflecting traffic for invalid requests.
The interesting stuff – ProxyPass
To set up Apache as a reverse proxy server you will need to enable mod_proxy. Some other common mods you may need are below.
- mod_proxy
- mod_http
- mod_headers
- mod_html
To enable mods in Ubuntu/ Debian you need to make sure they are installed, then enabled. For example, installing and enabling mod_proxy would look like this:
apt-get install libapache2-mod-proxy-html a2enmod mod_proxy
Once these mods are enabled, we can begin editing the Apache config. The locations of these vary depending on your Linux distribution. For RHEL based distributions, this will be your httpd.conf; for Debian based, sites-available/default.
Inside your VirtualHost tag create a Location tag which matches the external path you wish to use. For this example we will use /.
<Location /> # commands go here </Location>
Inside the Location tag add the proxy options ProxyPass and ProxyPassReverse followed by the site address which will be the target of the proxy. You will also need a couple of lines to allow access.
ProxyPass http://mywebsite.jamescoyle.net/ ProxyPassReverse http://mywebsite.jamescoyle.net/ Order allow,deny Allow from all
Outside of the location tags, towards the top of the virtual host add a few extras:
ProxyHTMLStripComments on ProxyRequests off SetOutputFilter proxy-html ProxyHTMLDoctype XHTML
If you will be proxying SSL traffic, you will also need to add:
SSLProxyEngine on
Restart apache or reload the settings for the changes to take effect:
service apache2 reload
You will now have a working proxy – all requests sent to / will be fetched from http://mywebsite.jamescoyle.net.
Example Apache reverse proxy VirtualHost
The below example shows an Apache VirtualHost which is listening on port 80. The confiiguration accepts requests on which match the www.jamescoyle.net hostname and proxys the requests to the backend server mywebsite.jamescoyle.net.
<VirtualHost *:80> ServerAdmin [email protected] ProxyRequests off DocumentRoot /var/www SSLProxyEngine on ProxyPreserveHost On ServerName www.jamescoyle.net ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel error <Location /> ProxyPass http://mywebsite.jamescoyle.net/ ProxyPassReverse http://mywebsite.jamescoyle.net/ Order allow,deny Allow from all </Location> </VirtualHost>