Password protecting a directory with an .htaccess file
Posted by zz-James Moir on 21 June 2016 04:07 PM
It may be necessary to password protect a directory or folder on your web site to prevent general public access or to prevent public download of Access databases stored within a folder.
Usually you can easily password protect a directory using the Plesk Server Administrator following the instructions here.
However, in some cases you may like to automate and control access to a directory by using a script to add usernames and passwords to an access list / password file or if you need to protect a directory on a sub domain you will need to use a .htaccess file as the Plesk Protected Directories feature is not available for sub domains.
The .htaccess file method only applies to Unix hosting plans.
Firstly, you will need to know the full path to your document root. This article will help you find this.
Then, in the directory you want to protect with HTTP authentication, create or upload a file named: .htaccess (remember to include the "." before the "htaccess"). Alternatively you can upload a text file called htaccess.txt and rename this once it has been uploaded to .htaccess
The .htaccess file should contain the following 4 lines:
For example, if your domain was example.com, then the third line would read:
The third line is the path to your password file.
Next, you need to create the password file itself. In the example above, .htpasswd is the file that will contain your access list. It is a special file that contains usernames and encrypted passwords that only the web server can read.
Since you don't have access to the Unix command line, you'll need to use an online tool to create the encrypted passwords. Try http://www.htaccesstools.com/htpasswd-generator/ and enter a username and password. It will create an output like user:ZHdYGYUr0N8PI.
Next create your htpasswd file, either as .htpasswd or as a htpasswd.txt file. Edit this file and enter the username and password combination. You can enter one per line.
So your htpasswd file will look something like this:
Upload this file to the path specified in your .htaccess file. If you have named the file as a txt file, remember to rename after uploading to .htpasswd.
Now when you enter the URL to your protected directory you should be prompted for the login and password.
The .htaccess and .htpasswd files are hidden files. So after uploading, you won't see them under your FTP client. To view them, you can either turn on 'Show Hidden Files' in your FTP client or use the File Manager under the Plesk Server Administrator. The File Manager can also be used to easily edit and rename the files.