Securing Webpages with .htaccess

Reading Time: 2 minutes

You will need to have following installed or available:

sudo and/or root privilages
text editor (nano or vi)

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/

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>
ServerAdmin [email protected]
DocumentRoot /var/www/
 <Directory /var/www/>
   AllowOverride All
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

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 πŸ˜€

For more in-depth detail and explanation visit Digital Ocean’s htaccess guide

The following two tabs change content below.

Keeran Marquis

Network Engineer
Keeran Marquis is a Network Engineer. His main goal is to learn everything within the Networking field, pick up a little bit of scripting, be a poor man sysadmin and share whatever he knows! All Posts are his own views, opinions and experiences, no guarantees they will work for you but point you in the right direction πŸ™‚
Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.