Home     SSI Lab     CSS Templates     CSS     Htaccess     Web Design     XHTML

Htaccess Tutorials

graphic-img   

SSI-D HOME

SSI LAB

CSS Templates

CSS

.Htaccess

Introduction

Experimental

Web Design

(X)HTML

HTML-Kit

Resources





Password Protection of Files

Introduction::

As well as protecting directories .htaccess can also be used to protect individual files or types of files.



Step 1 - Required Files:

As with protecting a directory there are two files you need to create to protect (and allow limited access to) your files, .htaccess and .htpasswd.
Note:: these are the file extensions and can only be called this. Do NOT name them something like mydirectory.htaccess they can ONLY be called .htaccess and .htpasswd

Also the . (dot, period, fullstop) is very important!



Step 2 - Creating the .htaccess file:

The .htaccess file is created as normal in a text editor. To protect individual files we can use the <FilesMatch> tag.

<FilesMatch secrets.htm>
AuthName "Restricted File"
AuthType Basic
AuthUserFile /user/home/www/directory/.htpasswd
require valid-user
</FilesMatch>

secrets.htm is obviously the name of the file you want to protect and ensure the location of the .htpasswd file is correct.



Step 3 - Protecting multiple files:

The easiest way to protect a number of files would be to place them all into a separate password protected directory but it is also possible to protect a number of files without protecting the whole directory.

As with the above example the same code is used for each file you want to protect.

<FilesMatch secrets.htm>
AuthName "Restricted File"
AuthType Basic
AuthUserFile /user/home/www/directory/.htpasswd
require valid-user
</FilesMatch>

<FilesMatch whispers.htm>
AuthName "Restricted File"
AuthType Basic
AuthUserFile /user/home/www/directory/.htpasswd
require valid-user
</FilesMatch>

It may be also possible to protect a number of files with the following method:

<Files secretA.htm,secretB.htm,secretC.htm>
AuthName "Restricted Files"
AuthType Basic
AuthUserFile /user/home/www/directory/.htpasswd
require valid-user
</files>

...although FilesMatch is the preferred method.
Ensure there are no spaces between the file names in the first line.



Step 3 - Protecting file types:

We can protect types of files or files which match a certain criteria by using <FilesMatch>. To protect the common image file types we can use the following:

<FilesMatch "\.(gif|jpe?g|png)$">
AuthName "Restricted"
AuthType Basic
AuthUserFile /user/home/www/directory/.htpasswd
require valid-user
</FilesMatch>

To protect just one type of format we can simplify the first line:

<FilesMatch "\.(png)$">

Here all files ending in .png are protected.


More information on <Files> & <FilesMatch>




Advertisement Sign up for free to PayBox.me today and get $25 just for joining AND earn up to $20 per day for participating.