Tuesday, March 10, 2015

How can I restrict IP addresses in .htaccess with the reverse proxy in front?

Since requests to your site are usually first handled by the Varnish reverse proxy, you can't use the sender IP address to block certain IP addresses in your .htaccess configuration file. The following will not work because all requests the web server receives will originate from the proxy address, and in consequence, no access will ever be allowed:

Order deny,allow
Deny from All

Allow from 1.2.3.4
Allow from 2.3.4.5

There is a way of checking the real sender address, though, because Varnish puts it in the HTTP header X-Forwarded-For.

A few additional lines make Apache check this HTTP header, too:

Order deny,allow
Deny from All

SetEnvIF X-Forwarded-For "1.2.3.4" AllowIP
SetEnvIF X-Forwarded-For "2.3.4.5" AllowIP

Allow from env=AllowIP
Allow from 1.2.3.4
Allow from 2.3.4.5

This ruleset will work both for requests handled by Varnish (Port 80) and directly handled by Apache (Port 81).

https://freistil.zendesk.com/entries/21852711-How-can-I-restrict-IP-addresses-in-htaccess-with-the-reverse-proxy-in-front-

No comments: