It's probably quicker to use htaccess since you won't need to run the php handler to run your php script. There's a similar answer that I gave for blocking IP addresses which utilizes the RewriteMap
. You'd just need something the other way around, instead of denying access from those IPs, grant access:
RewriteMap allow_ips txt:/path/to/allow_ips.txt
RewriteCond ${allow_ips:%{REMOTE_ADDR}|0} =1
RewriteRule ^protected/path - [L]
RewriteRule ^protected/path - [L,F]
The contents of the allow_ips .txt file would be:
12.34.56.78 1
11.22.33.44 1
etc.
The RewriteMap
directed must be in either the server or vhost config. You can define a map from htaccess, though you can use it there.
If you can't use maps, then you'll need to enumerate all the IPs with an Allow
. In the htaccess file in the directory you want to protect:
Order Allow,Deny
Deny from all
Allow from 12.34.56.78
Allow from 11.22.33.44
...
Is there a better way?
The best way is probably to implement a user/password via htpasswd. Here's a tutorial. Then you can put the Auth*
stuff in an htaccess file in the directory you want to protect and that's that. Simple.