Firstly, my apologies for the shocking title. It’s the best I could come up with though (If you can think of something that summarises this better please let me know :-)).
I’ve been asked about this on quite a few occasions now, the last one being PC-Mike over on the WHMCS forums; The question being “Is it possible to allow access to a directory from some IPs without using a user/pass, but still allow access from non-authorized IPs with a user/pass”. The answer is YES! in fact its really quite simple. Create an “.htaccess” file in the directory that you would like to protect and copy the following code into it.
Order deny,allow
Deny from all
AuthName "Auth Test"
AuthUserFile "/path/to/auth/file"
AuthType Basic
Require valid-user
Allow from 1.1.1.1 2.2.2.2 3.3.3.3
Satisfy Any
Obviously you need to replace “/path/to/auth/file” with the actual location of the Auth User file you want to use and also replace 1.1.1.1 2.2.2.2 3.3.3.3 with the IP address(s) that you would like to allow access without using a username and password. You can add as many IPs as you like here, just separate them by spaces!
If you already have an .htaccess file where you would like to use this, you will need to merge the above with it (making sure that there are no conflicting rules).
If you have any comments or questions. Please leave a comment below 🙂
August 16th, 2011 at 12:49 am
Ben, thank you for the useful page. I’m stumped on something. The “satisfy any” directive allows visualization of the .htaccess file for the directory it resides in.
Here’s what I do:
1. copy/paste just your code into my .htaccess file, changing the directories.
2. point browser to protected directory
3. enter proper user/pass
4. re-direct browser to http://www.website.com/test/.htaccess
I can see the entire contents of the file! GoDaddy was troubleshooting this and they found that it was the satisfy any directive. If I take it out the problem goes away. Any ideas?
September 27th, 2011 at 1:01 am
Hi Dave, sorry for this late reply, I’ve been rather busy and haven’t paid as much attention to my blog as I would have liked 🙁
I’m not sure why it is doing that, I have just done what you did and going to the .htaccess file returns a “Forbidden” error as expected. If it’s visible, make sure that the permissions on the file are as tight as possible and try adding the following:
<Files .htaccess>
order allow,deny
deny from all
</Files>