You can do it 4 steps:
1. Create a .htaccess file with the following in the to-be-protected folder:
In the folder, you want to protect, create a .htaccess file:
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /var/www/html/.htpasswd
Require valid-user
2. Create a .htpasswd file outside /var/www or in the same folder. Remove the dummy path and use your own. Also, use this generator to create the content of your .htpasswd file.
3. You’ve got to enable htaccess override in this file: /etc/apache2/sites-available/default
You would see None after “AllowOverride”, so change that to All:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
You can use secure shell and use this command to edit:
sudo nano /etc/apache2/sites-available/default
4. Finally, restart Apache2
sudo /etc/init.d/apache2 reload