Skip to content

Load balancing with WHM, NGINX, and mirrors

I have a project where I need to do a bit of load balancing to keep a website online for a very small window of time when it would receive an extremely high level of traffic.  I saw a dramatic increase in performance after simply installing NGINX, but I also wanted to be able to use mirrors and change the split of traffic during that peak time if we experienced any issues. NGINX does have a module for setting up upstream proxies to handle load balancing, but for this project redirects were simpler and more flexible.

This does only apply to virtual private servers or dedicated hosting – you won’t be able to run this kind of setup in a shared hosting environment.  Start by installing NGINX, below I have instructions on how to add NGINX if your site is on CPanel.

  1. cd /usr/local/src
  2. wget http://nginxcp.com/latest/nginxadmin.tar
  3. tar -xf nginxadmin.tar
  4. cd publicnginx
  5. ./nginxinstaller install

You will also need to delete the automatically generated vhost file for the domain/subdomain you want to change.  And you’ll need to re-delete it if your ever regenerate the vhosts.  You can do this by:

  1. cd /etc/nginx/vhosts/
  2. rm sub.domain.com

NGINX comes pre-installed with the split clients module.  This module is specifically designed for A/B testing, but it will also allow you to split up your traffic between different sites and allow you to adjust how much traffic each site receives.  If you’re using NGINX CP as I described above then you can either edit you NGIX config in WHM, or you can find the file at “/etc/nginx/nginx.conf” to edit from the shell.  In my example below I am also using the $http_referer variable to set-up a separate redirect specifically for direct traffic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
http {
 
split_clients "${remote_addr}" $mirror {
	33%	"http://google.com";
	33%	"http://yahoo.com";
	*	"http://bing.com";
}
 
server {
	listen 0.0.0.0:80;
	listen [::]:80;
	server_name sub.domain.com www.sub.domain.com;
 
	location / {
		add_header X-Cache "Redirect load balancing";
 
		if ($http_referer = "") {
			set $mirror "http://duckduckgo.com";
		}
 
		return 302 $mirror;
	}
}
 
}

REFERENCES

http://www.nginxcp.com/installation-instruction/
http://nginx.org/en/docs/http/ngx_http_split_clients_module.html
https://www.digitalocean.com/community/tutorials/how-to-target-your-users-with-nginx-analytics-and-a-b-testing
http://serverfault.com/questions/597671/load-balancing-in-nginx-with-redirect-rather-than-proxy

Published inOtherScripting

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *