How To Protect a Folder Using .htaccess From Command Line

By | August 28, 2008

We do often meet password protected directories on the Web. This is usually used to hide some information that should not be visible to all site users. Most common is .htaccess protection, that allows you to restrict users at Apache level and is also knows as http authentification. Today I will tell you how to protect your directory using command line.

As usually we need root access to the server and need to go to the folder which is waiting to be protected. First of all we need to create an .htaccess file that should contain the information that authentification is required to access this folder. The most common sample comes below:

AuthGroupFile /dev/null
AuthName “Closed User Group”
AuthType Basic
AuthUserFile /path_to_htpasswd_file/.htpasswd
require valid-use

Usually .htaccess and .htpasswd files are located in the same folder, but you can move .htpasswd anywhere you like: you will just need to point to its absolute location in .htaccess.  Then go to the directory where you’re planning to put your .htpasswd file.

Now we need to have username and password – that’s enough. The following command will create your .htpasswd file with login data so you can use it immediately.

htpasswd -bcm .htpasswd user password

You can read more about this command at Apache Site. But this command will help you to create a password file without any specific knowledge.

Please, note that .htpasswd is just the file name: you’re welcome to store your passwords in the files with any file names, but it would be better if it is started with a dot and if this file is stored in the directory that is not accessible from web.