Allow Location in NGINX Based on IP When Request Comes from Varnish

nginxvarnish

If Varnish is set as the default Cache in front of my NGINX backend, how can I check in the NGINX backend for the clients original IP and make a decision based on that?

I want to allow a certain directory only to certain IPs. Varnish being in front of NGINX, means that every request comes from 127.0.0.1. I'm thinking about setting some custom HTTP header, but how could I check that in conjunction with location ~ /folder/ {} section?

Best Answer

By default Varnish 4 would set X-Forwarded-For header as the client's real IP, but NGINX would ignore that unless you set it up explicitly.

Add these lines to your nginx configuration in the server block which makes use of the ngx_http_realip_module:

server {
    listen 80;
    set_real_ip_from   127.0.0.1;
    real_ip_header     X-Forwarded-For;
    <Other Server Options>
}

If you use Ubuntu, the module is already enabled by default. However for some linux distributions you might have to enable or install it manually. You can check the configured modules by:

nginx -V

Do not forget to reload nginx after you update the configuration:

sudo service nginx reload

Once nginx is able to get the client's real IP set by Varnish, you just need to place allow and deny options in the location blocks:

server {
    <Server Options>
    location ~ /folder/ {
        allow <IP to whitelist>;
        deny all;
        <Location Options>
    }
}