To restrict access to a Web page, you can use the authentication modules and methods provided by Apache and third parties to authenticate the user's credentials (such as user name and password). Some modules support identity authentication through a variety of databases, including NIS and LDAP.
User authentication directives are usually placed in the. htaccess file. The following is a basic. htaccess file using the Apache Default Authentication module (Mod_auth). When this file is placed in/var/www, it causes Apache to require the user to enter a password for authentication before the browser can access the content in the/var/www directory hierarchy. When applied, it is replaced with the corresponding value of the local server.
# Cat. htaccess
authuserfile/var/www/.htpasswd
Authgroupfile/dev/null
AuthName "Browser dialog box query"
AuthType Basic
Require Valid-user
/VAR/WWW/.HTPASSWD is a typical absolute pathname of a. htpasswd file, and the user will see the String Browser dialog box query in a dialog box asking for a username and password.
The second line of the previous. htaccess file closes the group functionality. Line four specifies that the user's authentication type is basic, which is also the default setting for the Mod_auth module. The last line tells Apache which users can access the protected directory. The Valid-user entry authorizes any user (user name in the Apache password file and the password entered correctly) to access the directory.
As long as Apache can read its password file, the file can be placed anywhere on the system. It is also safe to put this file in the same directory as the. htaccess file because, by default, Apache will not respond to requests for any file whose name begins with. Ht. However, be sure not to change the httpd.conf configuration file to prevent Apache from responding to a request for a file whose name begins with. Ht.
The following command creates a. htpasswd file (–c) with a SAM entry in the working directory. Omit the –C option to add a user or change a password in an existing. htpasswd file.
$ htpasswd-c. htpasswd Sam
New Password:
Re-type New Password:
Adding password for user Sam
The default httpd.conf file includes the allowoverride none directive for/var/www. To enable Apache to process user authentication directives (such as reading. htaccess files), you must change this directive to allowoverride authconfig or delete it.
When Apache has been configured to handle the. htaccess file, when it receives a request for a file, it must traverse the directory hierarchy up from the requested file to the root directory, looking for the. htacess file to determine whether it can provide the requested file. This search may affect performance. Typically, performance degradation is less severe, but if performance is critical, the problem will be tricky.