How To Put Nginx Behind Haproxy ?

Nginx is a great webserver and multiple Nginx servers behind a Haproxy load balancer works flawless. Although Nginx can be also used as a load balancer, we strongly recommend using Haproxy if you are planning to run a high traffic website. In this tutorial, our goal is to create a Haproxy configuration, which uses Nginx servers for its backend. This configuration has been tested on a website that receive more than 80,000 people in real time and Haproxy handled it perfectly.

How To Install Haproxy On Centos?

By running the following commands, we can install Haproxy load balancer in less than a minute:

The default configuration file which comes with Haproxy is located at /etc/haproxy/haproxy.cfg. We will edit this file in order to setup our load balancer for Nginx servers.

Below we are posting a configuration file which might seem very long to you. The reason we are posting such a long file is that it contains many features of Haproxy and addresses many issues that might take too much time to solve even if you try to lookup online. Unfortunately, Haproxy’s official documentation is not very user friendly and does not contain too many examples.

Haproxy Configuration For Nginx

The configuration file contains the following in summary:

  • It uses two backends. One for subdomain and one for everything else. It uses different weight distribution for the Nginx servers.
  • It can redirect a visitor to yahoo.com if it detects a bad referrer. (Pointless but needed if your boss hates the referrer)
  • It can display custom error pages for the response codes listed above.
  • It uses GZIP compression on the file types listed above. You can see the compression rates on Haproxy’s stats page.
  • It enables Haproxy’s stats page on port 9000 which can be accessed as http://your-ip-address:9000/haproxy_stats
  • It can track connections and reject abusers. A little protection for your load balancer.
  • It accepts cookie sizes up to 32k. You should also set header client buffer size on your Nginx servers.

 

How To Setup Haproxy Log Files ?

The following lines from the configuration file above tells Haproxy how to log:

In order to see the Haproxy logs, we should make some modifications on rsyslog. First, edit /etc/rsyslog.conf and make sure these lines are uncommented:

After saving rsyslog.conf, now create a new file at /etc/rsyslog.d/haproxy.conf and put the following lines inside:

Great! Now its time to restart rsyslog and haproxy in order to run your new load balancer.