Securing Webpages with .htaccess
You will need to have following installed or available:
sudo and/or root privilages
text editor (nano or vi)
apache2-utils
Firstly you will need to enable apache to allow overrides. You will need to edit your apache config file.
sudo nano /etc/apache2/sites-available/exmaple.co.conf
You will need to add the AllowOverride All
within the section. You have to manual set the directory section to the folder you want to protect. In this example, I just wanted to protect anything within the html folder
AllowOverride All
Normally (from my experience) their isn’t a Directory section, so you can just copy and paste the code into your file. In the end it should look something like this:
<VirtualHost \*:80>
ServerName example.co
ServerAlias example.co
ServerAdmin webmaster@localhost
DocumentRoot /var/www/example.co/html
<Directory /var/www/example.co/html/>
AllowOverride All
</Directory>
ErrorLog ${APACHE\_LOG\_DIR}/error.log
CustomLog ${APACHE\_LOG\_DIR}/access.log combined
</VirtualHost>
Once you have saved and closed, you will need to apply the change via an apache restart
sudo service apache2 restart
Next, create the .htaccess
touch .htaccess
Within the .htaccess, you will need to add the following details:
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /home/example/.htpasswd
Require valid-user
Save and close, once the details have been added.
Finally, we will need to add users that can have access to the newly restricted folder
sudo htpasswd -c /home/example/.htpasswd {username}
You will prompted to enter a password that will not be shown.
If you wanted to additional users, you will use the same command without -c
sudo htpasswd /home/example/.htpasswd {username}
Now you should be able to browser to the website/folder and be greeted with login prompt :D
For more in-depth detail and explanation visit Digital Ocean’s htaccess guide