Using Apache – Secure a website or a particular subdirectory

Using Apache to secure a website or a particular subdirectory:

1. Create a password .htpasswd file on the webserver containing username and password (or a sub directory if you want security on a particular sub directory only).

$ cd /path/to/secure_folder
$ htpasswd -b -c .htpasswd username pwd

2. Create .htaccess file in the sub directory (or root) where you need security containing the following:

	AuthUserFile /www/secure_path/.htpasswd
	AuthName "Secure Area"
	AuthType Basic

	<Limit GET POST>
		require valid-user
	</Limit>

That’s all.

Note:
In case the above .htaccess file conflicts with the main .htaccess of the website or web application in the root directory you may drop the following line at the top of the main .htaccess file:
ErrorDocument 401 default

It should not mess with HTTP codes of the web pages in the root directory or other directories. But just in case you must check the HTTP code(s) in the Developer Tools under Network > Headers > General > Status Code in Google Chrome. It should say 200 OK.