Block IP Addresses in .htaccess behind Load Balancer

Sometimes you need to block access from certain IP addresses to your web site. It is easy to do in .htaccess file if you are running Apache. What if your server is behind a load balancer ? The code below lets you block IP addresses when your server is behind AWS load balancer.

php_value memory_limit 1024M
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<Files *>
SetEnvIF X-FORWARDED-FOR "123.567.89.10" AllowIP
SetEnvIF X-FORWARDED-FOR "123.45.67.89" DenyIP
#SetEnvIF REMOTE_ADDR "1" AllowIP #Local IP

Order allow,deny
Allow from all
Deny from env=DenyIP
</Files>
Share this article

Similar Posts