Ano-Tech Computers
Enter keyword:

Restricting access to web pages using Apache
Problem:
This article describes how to restrict access to web pages on a webserver running Apache. The method described may not work with ancient versions, see www.apache.org for details.
 
Solution:
Step one is to create a file called ".htaccess" in the directory you wish to protect. This filename is automagically recognized by Apache. Keep in mind that all subdirectories and files in that directory will require password authentication, so you may have to re-organize your web site to make sure users can still access any part of your site that should not require authentication.

Here is an example .htaccess file:
"deny from all"
"AuthType Basic"
"AuthUserFile /home/httpd/html/user/yourlogin/public_html/directory/.htpasswd"
"AuthName My_Protected_website"
"require valid-user"
"satisfy any"

You need to change a few things to match your setup. "yourlogin" must be replaced with your login name, and "directory" must be replaced with the subdirectory within public_html that you wish to protect. Finally, "My_protected_website" is the string that will be shown in the password prompt. This string MUST NOT contain any spaces or special characters, or Apache will refuse to accept your .htaccess file!

Second, you need to create the ".htpasswd" file that you referred to in ".htaccess". This file is created and maintained using a utility called "htpasswd".

Create the file and insert the first user by typing
"htpasswd -c .htpasswd jane"
You will then be prompted for jane's password before the file ".htpasswd" is created.

To add more users, type
"htpasswd .htpasswd joe"
You will then be prompted for jane's password before the user "joe" is added to the ".htpasswd" file.

The resulting file looks something like this:
jane:HqD0xxqnn1ujk
joe:7C8LGt6N5XXoQ

You can remove users by simply removing lines from the file, using a text editor of your choice.

Finally, any changes to ".htaccess" and ".htpasswd" become effective immediately, there is no need to reload/restart Apache. Most browsers will "cache" the authentication though, so you'll probably need to restart your browser in order to test changes made.

For more information about using .htaccess files, see
http://httpd.apache.org/docs/mod/mod_auth.html

 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles