1

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?

2

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>
    }
}
  • Very nice answer, thank you, even though Michael Hampton answerred first :) Now the file gets downloaded instead of rendered by PHP - do you have an idea? – chevallier Sep 4 '18 at 13:02
  • @chevallier Now you have a completely different and likely unrelated problem. – Michael Hampton Sep 4 '18 at 13:03
  • Do you have fastcgi setup to serve PHP? You will need to proxy requests to PHP file via the FCGI protocol in the location block. – Victor Wong Sep 4 '18 at 13:04
  • @MichaelHampton - yes, this is another problem, sorry for posting it here, I'll see how to fix that. You helped me with my original problem, thank you guys! – chevallier Sep 4 '18 at 13:08

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.