Today I needed to password protect a single CGI program written in Perl using Basic authentication. I was, like most people, aware of how to protect an entire directory using the .htaccess file on an Apache HTTP server. But is there a way to password protect a single file in the cgi-bin directory? The answer is yes.
In order to protect a file, just replace Directory directive with Files:
<Files admin.cgi>
AuthType Basic
AuthName "Protected Access"
AuthUserFile /usr/local/apache/passwd
Require valid-user
</Files>
By entering the above lines in a file named .htaccess and replacing "admin.cgi" with the actual name of the file you want to protect, and using the actual path to the file containing the passwords, your file should be password protected. So if you try to access it using a web browser a window should pop up in which you can enter your credentials.
If you have several files that need protection you might want to check out the FileMatch directive, which lets you specify a regular expression.
Finally be aware that Basic authentication sends the password from the browser to the server encoded but certainly not encrypted and hence is very sensitive to eavesdropping. If possible use for example Digest authentication, see mod_auth_digest.