Nginx ip_hash behind proxy (Cloudflare)

cloudflarenginxreverse-proxy

We use nginx for our load balancing, and we need ip_hash to guarantee our server work fine.

When we started using cloudflare, most our requests go for one server as it seems all of them are identified only by cloudflare's IP.
We would like to balance it better, and it would be good that the ip_hash used the header CF-Connecting-IP that cloudflare puts on requests.

Anyone knows how to do this?

upstream backend {
    ip_hash;
    #proxy_next_upstream_timeout 30;
    server localhost:8080 max_fails=2 fail_timeout=180;
    server somethign:8080 ;
    server something2:8080;
}

Best Answer

Cloudflare has these ip ranges, you can use nginx built-in real_ip module and setup headers properly https://www.cloudflare.com/ips

set_real_ip_from   204.93.240.0/24;
real_ip_header     CF-Connecting-IP;

https://support.cloudflare.com/hc/en-us/articles/200170706-Does-CloudFlare-have-an-IP-module-for-Nginx-