Skip to main content

How to Password-Protect a Website Directory

You can password-protect a specific directory or folder on your website using the .htaccess file within cPanel. This ensures that only users with a valid username and password can access the content in that specific folder.

Before you begin

You will need:

  • A cPanel account

  • Access to the File Manager or an FTP client

  • The specific path to the directory you wish to protect

Password-protect a directory using .htaccess

To protect a directory, you must use the Apache .mod_authz_host or .htaccess method. This process involves creating a password file and then referencing that file in your .htaccess configuration.

  1. Log in to your cPanel account.

  2. Open the File Manager.

  3. Navigate to the directory you want to protect (e.g., /public_html/private-folder).

  4. Inside that folder, locate or create a file named .htaccess.

  5. Edit the .htaccess file and add the following lines:

    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /home/username/.htpasswd
    Require valid-user

  6. Replace /home/username/.htpasswd with the actual full server path to your password file. Note: You can find your home directory path in the File Manager sidebar or by checking the "Home" directory.

  7. Save the changes to the .htaccess file.

Warning: Incorrectly editing the .htaccess file can cause a "500 Internal Server Error," making your website inaccessible. Ensure the path to the .htpasswd file is absolute and correct before saving.

Create the .htpasswd file

To generate the file that contains the encrypted credentials for your users:

  1. In the File Manager, navigate to your home directory (the folder above public_html).

  2. Create a new file named .htpasswd.

  3. You must populate this file with encrypted credentials. You can use an online "htpasswd generator" or a command-line tool to create the entry.

  4. Enter your desired username and password into the generator and paste the resulting string into the .htpasswd file.

  5. Save the file.

Confirm the result

  • Navigate to the protected directory via a web browser.

  • A login prompt should appear before the page loads.

  • Enter the credentials you created in the .htpasswd file.

  • The page should load successfully only after the correct credentials are provided.

Limitations

  • This method requires the server to be running on an Apache or LiteSpeed web server.

  • This protection only applies to the specific directory where the .htaccess file is located; it does not protect the entire website unless the file is placed in the root directory.

  • This does not provide security for the underlying files if accessed via direct paths that bypass the .htaccess rules.

Did this answer your question?