Restricting Access by IP

The AWS Elastic Loadbalancer prevents the underlying Apache-based web servers from seeing the true IP address of the users in the traditional way.  This unfortunately means that the standard mechanism for restricting access to a site via source IP does not work. The ELB does provide this data, however, by means of a special header called X-Forwarded-For. We can use this header along with some SetEnvIf directives to set the value of an environment variable based on the IP address. Once that environment value is set, we can restrict access to the site based on it rather than the client’s IP directly.

Here are some examples.  These directives can go in either the top-level Apache config files or individual .htaccess files.

# Restrict to OSU networks
SetEnvIf X-Forwarded-For "^128\.146\." ip_ok
SetEnvIf X-Forwarded-For "^164\.107\." ip_ok
SetEnvIf X-Forwarded-For "^140\.254\." ip_ok
SetEnvIf X-Forwarded-For "^2620:0:1a10:" ip_ok
SetEnvIf X-Forwarded-For "^172\.(1[6789]|2[0-9]|3[01])\." ip_ok 
SetEnvIf X-Forwarded-For "^3\.16\.225\.230$" ip_ok 
SetEnvIf X-Forwarded-For "^3\.14\.116\.154$" ip_ok
SetEnvIf X-Forwarded-For "^3\.12\.52\.221$" ip_ok 
Order deny,allow
Deny from all
Allow from env=ip_ok
# Block only bad IP ranges and let everyone else through
SetEnvIf X-Forwarded-For "^1\.2\.3\.4 ip_bad
SetEnvIf X-Forwarded-For "^5\.6\.7\." ip_bad
Order allow,deny
Allow from all Deny from env=ip_bad
# Allow from OSU networks only _except_ for a few specific IPs
SetEnvIf X-Forwarded-For "^128\.146\." osu_ip
SetEnvIf X-Forwarded-For "^140\.254\." osu_ip
SetEnvIf X-Forwarded-For "^164\.107\." osu_ip
SetEnvIf X-Forwarded-For "^128\.146\.1\.2" bad_osu_ip
SetEnvIf X-Forwarded-For "^164\.107\.3\.4" bad_osu_ip
Order allow,deny
Allow from env=osu_ip
Deny from env=bad_osu_ip
# Example using mod_rewrite to block bad IPs instead
RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-For} ^1\.2\.3\.4$ [OR]
RewriteCond %{HTTP:X-Forwarded-For} ^5\.6\.7\.
RewriteRule .* - [F]

# Or if you'd prefer an error page to a 'forbidden' code then replace last line with
RewriteRule .* http://www.osu.edu/err/404.php [L,NE,R=301]

Notice that the IPs must be in regular expression form rather than CIDR, IP/netmask, or other standard ways of denoting IPs. This is because we’re actually doing a string comparison instead of a more intelligent range match.

Multiple SetEnvIf statements produce logical OR behavior. If you need logical AND then you need to build it into the regexp.

Unfortunately, due to the way Apache’s security works and the way it sets its variables behind the scenes, you cannot use mod_rewrite to fudge the REMOTE_ADDR value with X-Forwarded-For. Any applications that use REMOTE_ADDR will need to be reconfigured or modified.


Need More Information?

Is OSU Web Hosting right for you? Check your eligibility.

More questions? Check the support section or contact us.

Ready to get started? Request hosting now!