Select a username and password pair. Generate the requisite hash for the password. Can use online tools like: https://hostingcanada.org/htpasswd-generator/
Create the .htpasswd file outside the publicly accessible directory. A directory right above public_html is good.
nano .htpasswd
Paste in the username and password pair generated:
user1:$2y$10$TMp2RJGcLAT1COY3owX72eRj/W.b9SUikzKbdCPeBJsBb8rlnayim
The above was generated for username user1 with password wyaJBB729chydNTK
Set the right permission for the .htpasswd file.
chmod 644 .htpasswd
Navigate to the directory you wish to restrict access to and begin to create the .htaccess file.
nano .htaccess
Write in the following lines:
AuthName "Restricted Access"
AuthType Basic
AuthUserFile /var/www/thecapiztimes.com/.htpasswd
Require valid-user
“Restricted Access” is just arbitrary text.
AuthUserFile is the full path to the .htpasswd file that was created.
To protect only a file, the the Authentication directives must be enclosed within the <Files> flag like so:
<Files admin.php>
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/username/example.com/.htpasswd
Require valid-user
</Files>
To protect multiple files, the Authentical directives must be enclosed by the <FilesMatch> flag like so:
<FilesMatch "^(admin|staff).php$">
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/username/example.com/.htpasswd
Require valid-user
</FilesMatch>
To make this work for a sub-directory in a WordPress installation, the ErrorDocument directive must be invoked like so:
ErrorDocument 401 default
And to display an index of files, add in the Options directive like so:
Options +Indexes
So, protecting an entire subdirectory for a WordPress installation the .htaccess would be like so:
ErrorDocument 401 default
Options +Indexes
AuthName "Restricted Access"
AuthType Basic
AuthUserFile /var/www/thecapiztimes.com/.htpasswd
Require valid-user
References:
https://help.dreamhost.com/hc/en-us/articles/216363187-Password-protecting-your-site-with-an-htaccess-file
https://hostingcanada.org/htpasswd-generator/