Allow location in NGINX based on IP – request comes from Varnish

Allow location in NGINX based on IP – request comes from Varnish

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 I'm thinking about setting some custom HTTP header, but how could I check that in conjunction with location ~ /folder/ {} section?


Answer 1:

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;
    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>