Monday, December 9, 2013

Block access to files by IP using X-Forwarded-For

What is the purpose of blocking by X-Forwarded-For IP, instead of the REMOTE_ADDR?

Sometimes a site may be behind a reverse proxy and it may not be possible to add a rule to block a file by IP at the reverse proxy level.  If the reverse proxy is passing the remote client IP in a header like X-Forwarded-For, you can still block by client IP.

Match the header to an IP address and assign it to an environment variable in Apache.  Here is an example of a complete configuration to block remote access to a wordpress login page, except for a certain range of IPs:

<files wp-login.php>
order deny,allow
deny from all
SetEnvIf X-Forwarded-For "192\.168\..*" LocalAccess
SetEnvIf X-Forwarded-For "10\..*" LocalAccess
Allow from env=LocalAccess
</files>

If the IP contained in the X-Forwarded-For header matches one of the regular expressions, it will populate the "LocalAccess" environment variable.


No comments:

Post a Comment