Skip to main content

How to forward the real client IP to a webserver NGINX behind a GCP Load Balancer

Purpose: We want to protect the origin server from being hit directly over the internet so we make sure only CDN/WAF connect to the backend also known as Origin Protection.

Scenario: 




CDN+WAF---->GCP Load Balancer --->VM Nginx


Solution:

Modify Nginx Configuration

...

location / { 
    allow 100.100.100.0/24; //Change with your CDN/WAF source IP that connects to the backend.
    deny all;
}

...

set_real_ip_from 1.1.1.1/32; // Change with your LB Public IP address
set_real_ip_from 130.211.0.0/22; // Private IP range for GCP Load Balancers
set_real_ip_from 35.191.0.0/16; //Private IP range for GCP Load Balancers
real_ip_header X-Forwarded-For; 
real_ip_recursive on;

...

Save and restart the services.

Check the Log

tail -f /var/log/nginx/access.log

tail -f /var/log/nginx/error.log


If there is client over the internet hit directly IP the load balancer, it will be blocked by Nginx (403 Forbidden)
you should see that the client source IP that is not whitelisted in the Nginx config will be denied as well.



References: 


Comments