Whitelisting servers from behind an AWS Elastic Load Balancer with Apache
by Sangraal on Apr.02, 2010, under AWS, Programming, Systems, Technology
Sometimes you need to limit access of a web directory to a specific set of IP addresses. Normally this is pretty straightforward with the <Directory>, <Location>, or <LocationMatch> directives in Apache’s config file.
For instance, if I wanted to limit access to a single IP address 10.0.0.1, my config might look like this:
<LocationMatch "/protected*/">
Order Deny,Allow
Deny from all
Allow from 10.0.0.1
</LocationMatch>
But when your Apache server is behind Amazon’s Elastic Load Balancer, it get’s a little trickier. From Apache’s perspective, all requests are coming from the ELB’s IP address. Thankfully, Amazon includes a HTTP Header X-Forwarded-For with the IP address of the original host. This makes it possible to detect and restrict access to a directory by IP with a few little Apache config changes.
The example above with the addition of an Apache directive called SetEnvIf results in the same behavior and works both standalone or behind any load balancer that supports the X-Forwarded-For header.
SetEnvIf X-Forwarded-For 10.0.0.1 my-whitelisted-ip
<LocationMatch "/protected*/">
Order Deny,Allow
Deny from all
Allow from env=my-whitelisted-ip
Allow from 10.0.0.1
</LocationMatch>
The addition of the SetEnvIf directive tells Apache to set an environment variable called my-whitelisted-ip if the X-Forwarded-For header matches my pattern, in this case 10.0.0.1. Inside the LocationMatch directive, I’m using the ‘Allow from’ directive to only let the request through if that environment variable exists. You can add multiple SetEnvIf directives to set the same environment variable to perform more complex checks.
As a side note, ELB’s can also mess with the logging of client IP’s. You can use the X-Forwarded-For header to solve this problem as well, here’s a good blog post explaining how to accomplish that.
1 Comment for this entry
1 Trackback or Pingback for this entry
-
Amazon ELB and Apache | Andrew Eells dot com
March 18th, 2011 on 4:08 pm[...] very helpful blog posts I found explaining explain both how to whilelist a particular request by IP address and how to set up yourApache logging behind the ELB to capture [...]
October 13th, 2011 on 10:57 pm
I tried this but the load balancer has a health check file “ping.html” and if the load balancer can’t hit this file, then we get a 503 server at capacity error when we try to load the site. This is what I’m trying, but it’s not working:
SetEnvIf X-FORWARDED-FOR my.136.ip.address allowedip
order deny,allow
deny from all
allow from allowedip
Order Allow,Deny
Allow from all