How to protect a folder with .htaccess on Apache Web Server in AWS EC2 instance?

Today we will learn how to use Apache’s .htaccess file to protect our private page on our website.Apache’s .htaccess file is powerful file that control high-level configuration of our website.Common use of .htaccess file are

  • Authentication
  • Mod _Rewrite
  • Custom Error Pages
  • Server Side Includes
  • Setting Server Time Zone
  • Mime Types

Now, we learn how to use Authentication feature of .htaccess file.We use .htaccess Authentication to protect our private folder with password on our webserver.To use .htaccess file you need to change “AllowOverride None” to “AllowOverride All” in httpd.conf file.So connect your EC2 instance and run the following command

sudo nano /etc/httpd/conf/httpd.conf

Find the following sentences,

<Directory "/var/www/html">

Options FollowSymLinks

AllowOverride None

Require all granted

</Directory>

And then,change “AllOverride None” to “AllOverride All”.

Now,you can use .htaccess file.To protect your folder with password create .htaceess file under the folder that you wish to protect with password.In this tutorial,root folder of Apache webserver is /var/www/html.I want to protect Admin folder under root folder.So,I create .htaccess file under Admin folder by the following command,

sudo nano /var/www/html/Admin/.htaccss

Write down following sentences in .htaccess file.

AuthType Basic

AuthName "Password Protected Area"

AuthUserFile /var/www/html/.htpasswd

Require valid-user

And then save and exit, Ctl+x.

AuthUserFile is the file path of .htpasswd file.

I created .htpasswd file under root folder by the following command.

sudo nano /var/www/html/.htpasswd

In .htpasswd file create User name and Password by the following pattern,

iamusername:iampassword

To create .htpasswd file i recommed joeswebtools.

You can place the .htpasswd file pretty much anywhere other than your web folder.But AuthUserFile path is must be correct.

To confirm that your content is protected, try to access your restricted content in a web browser. You should be presented with a username and password prompt that looks like this:

Have a nice day!

Leave a Reply

Your email address will not be published.