Hypister Hypister - 3 months ago 21
Apache Configuration Question

Too many redirects error

My .htaccess file has 3 Rewrite rules, but I'm facing a redirect issue:

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REMOTE_ADDR} =IP TO BLOCK GOES HERE
RewriteCond %{REMOTE_ADDR} =ANOTHER IP TO BLOCK GOES HERE
RewriteCond %{REQUEST_URI} !^/blocked
RewriteRule ^(.*)$ http://www.myhost.com/blocked [R=307,L]

RewriteCond %{REMOTE_ADDR} !=AUTHORIZED IP HERE
RewriteCond %{REQUEST_URI} !^/maintenance
RewriteRule ^(.*)$ http://www.myhost.com/maintenance [R=307,L]

ErrorDocument 400 /400.php
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php


The problem is if a blocked IP tries do access the site when it is under maintenance, I receive an "Incorrect redirect" error. How to stop Rewrite processing if the IP is one of the denied ips?

Answer

You can use:

RewriteEngine On

RewriteBase /

RewriteCond %{REMOTE_ADDR} =IP TO BLOCK GOES HERE
RewriteCond %{REMOTE_ADDR} =ANOTHER IP TO BLOCK GOES HERE
RewriteCond %{REQUEST_URI} !^/blocked
RewriteRule ^ http://www.myhost.com/blocked [R=307,L]

RewriteCond %{REMOTE_ADDR} !=AUTHORIZED IP HERE
RewriteCond %{REQUEST_URI} !^/(?:maintenance|blocked)
RewriteRule ^ http://www.myhost.com/maintenance [R=307,L]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

ErrorDocument 400 /400.php
ErrorDocument 401 /401.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 500 /500.php