Tag Archives: .htaccess security webserver

Protecting files and directories on webserver using .htaccess and .htpasswd files

You can protect specific files and directories on your webserver using .htaccess and .htpasswd files.
The following is an example to get you started.

Create a simple text file using your favourite text editor and name it .htpasswd
Now you need to write the following into your file in a line:

username:password

But it is not put as it is, rather it is encrypted and then entered into the file.
For example this is what it looks like on my system

amit:8ZtgChaul6rcM

You can use this link to encrypt your file:

Here, we are done with the .htpasswd file.

Lets move to the .htaccess file. One can use the .htaccess file to prevent the access to certain files and/or directories on the webserver.
Create a new text file named .htaccess and put the following lines to the .htaccess file.

AuthUserFile /absolute/path/to/.htpasswd
AuthGroupFile /dev/null
AuthName ‘Protected Area’
AuthType Basic

Now depending on you requirement, you may add the following lines to the file.

  • If you want to prevent access to a directory, then put the .htaccess file into the directory which needs to be protected and add the following lines to it. Note that these lines are in addition to the 4 lines aforementioned.

<limit GET PUT POST>
require valid-user
</limit>

the whole .htaccess file will look something like this:

AuthUserFile /opt/lampp/htdocs/gk/.htpasswd
AuthGroupFile /dev/lampp/htdocs/gk/.htpasswd
AuthName ‘NO TRESPASSING’
AuthType Basic
Allow From All

<limit GET PUT POST>
require valid-user
</limit>

  • If you want to prevent access to a file, then put the .htaccess file into the directory which contains the file to be protected and add the following lines.

<Files file-to-be-protected.extension>
Deny From All
</Files>

The usage of .htaccess and .htpasswdd given here are very basic. For a detailed tutorial, take a look at this.

Advertisements