How to Password Protect Files/Directories on Apache2 with .htpasswd & .htaccess

Note: You must have sudo/root access for some commands.

Step 1: Create the .htpasswd file

The htpasswd file is where you set the specific username and password. To generate this file run the following command:

htpasswd -c /path/to/directory/.htpasswd username

(Replace /path/to/directory/ and username with your website's path and desired username.)

It will then ask for your desired password. The resulting file will be encrypted. If you want to add additional users, run the command again without the -c flag as ahown below:

htpasswd -c /path/to/directory/.htpasswd username

Step 2: Create the .htaccess file

You will want to make sure to place the .htaccess file in the directory you want password protected.

Copy and paste the following code into the .htaccess file:

For directory:

AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /path/to/directory/.htpasswd
Require valid-user

For file

<Files file.ext>
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /path/to/directory/.htpasswd
Require valid-user
</Files>

Note: Before entering passwords, make sure you are connecting to the site with HTTPS. If you use certbot for Let's Encrypt certificates, I suggest enabling automatic redirecting to HTTPS.