Search code examples
apache.htaccesshttp-redirectmod-rewriteurl-rewriting

How do I restrict specific IP ranges from viewing a specific page in .htaccess?


I'm trying to only allow specific IP ranges to access /user/login. Denying anything under the /user sub-directory would suffice.

So far I've tried:

<Location /user>
    Order deny,allow  
    Deny from all
    Allow from 123.45.116.0/24
    Allow from 123.225.232.0/23
    Allow from 123.225.114.0/23
    Allow from 123.9.53
</Location>

and

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^123\.45\.116\.0/24$
RewriteCond %{REMOTE_ADDR} !^123\.225\.232\.0/23$
RewriteCond %{REMOTE_ADDR} !^123\.225\.114\.0/23$
RewriteCond %{REMOTE_ADDR} !^123\.9\.534$
RewriteRule ^user/? - [F,NC]

and

 RewriteCond %{HTTP:X-FORWARDED-FOR} !^123\.45\.116\.0/24
 RewriteCond %{HTTP:X-FORWARDED-FOR} !^123\.225\.232\.0/23
 RewriteCond %{HTTP:X-FORWARDED-FOR} !^123\.225\.114\.0/23
 RewriteCond %{HTTP:X-FORWARDED-FOR} !^123\.9\.53\.
 RewriteRule ^(user|user/login) - [F]

no luck. Could anyone out there please help? I always struggle with htaccess.


Solution

  • In case you are looking to allow specific IP ranges(taken from your efforts) and URI should start from user then you may try following. So in case IP addresses doesn't come in mentioned IP ranges and its trying to hit URL like http://lcoalhost:80/user(as an example) then it will Forbid that page. Here is Online demo for regex used

    RewriteEngine ON
    RewriteCond %{REMOTE_ADDR} !^123\.45\.116\.([0-9]|[0-1][0-9]|2[0-4])$
    RewriteCond %{REMOTE_ADDR} !^123\.225\.232\.([0-9]|[0-1][0-9]|2[0-3])$
    RewriteCond %{REMOTE_ADDR} !^123\.225\.114\.([0-9]|[0-1][0-9]|2[0-3])$
    RewriteCond %{REMOTE_ADDR} !^123\.9\.53
    RewriteRule ^user/? - [F,NC,L]
    

    Please make sure you clear your browser cache before testing your URLs.



    OR you could use a single condition also, use either above OR following only at a time.

    RewriteEngine ON
    RewriteCond %{REMOTE_ADDR} !(^123\.45\.116\.([0-9]|[0-1][0-9]|2[0-4])$)|(^123\.225\.232\.([0-9]|[0-1][0-9]|2[0-3])$)|(^123\.225\.114\.([0-9]|[0-1][0-9]|2[0-3])$)|(^123\.9\.53)
    RewriteRule ^user/? - [F,NC,L]