1. Home
  2. Support
  3. Scripting
  4. Protecting a Directory Using .htaccess and .htpasswd (Linux/Apache)

Protecting a Directory Using .htaccess and .htpasswd (Linux/Apache)

The .htaccess method of protecting your files and directories is one of the easiest ways to add more security to your website. You will require two files, a .htaccess and a .htpasswd. You’ll also need to know your root directory, which is usually something a long the lines of /hsphere/local/home/your_username_here/.

You should be able to use your FTP client of choice, such as FileZilla or Cyberduck, to create and edit these files.

The .htpasswd File

The .htpasswd file is the file we’ll use to store all the usernames and passwords of the users authorised to have access to the site. The usernames are stored in plaintext, where as the passwords are hashed using the MD5 algorithm.

1. Create a .htpasswd file in a directory named /protect-me-dir/.

2. Visit our user:password generator.

3. Input the user:password combination you wish to use to gain access to your site with into the corresponding fields and click Submit.

4. Follow the instructions and Copy the output specified and place it within your .htpasswd file.

5. Save the file once you have inputted all the users you wish to have access to the site.

The .htaccess File

1. If you haven’t already, create a .htaccess file within the directory you wish to protect.

2. Add into the .htaccess file the following code, making sure you get the AuthUserFile correct. It should be the same location where your .htpasswd file is located.

AuthType Basic
AuthName "restricted area"
AuthUserFile /hsphere/local/home/your_username_here/protect-me-dir/.htpasswd
require valid-user

You can use the bottom part of the output from the method above if you wish, making sure you alter the correct parts.

3. Save the file after making sure the code is correct.

When visiting the site in certain browsers, your website/directory should now be locked behind an authentication window. You will need to input the username and password of a verified user stored in the .htpasswd file in order to gain authorised access to the site.

Click here for full details

Classification: Public
Last saved: 2019/10/14 at 09:47 by