Tuesday, July 23, 2013

Password-Protect a Directory With .htaccess


Warning: On at least some versions of Ubuntu, .htaccess files will not work by default. See EnablingUseOfApacheHtaccessFiles for help on enabling them.
Create a file called .htaccess in the directory you want to password-protect with the follwing content:
 
AuthUserFile /your/path/.htpasswd
AuthName "Authorization Required"
AuthType Basic
require valid-user


instead of valid-user, you can also add the users you want directly
If you want to password protect just a single file in a folder add the following lines to the .htaccess file:
 
<Files "mypage.html">
  Require valid-user
</Files>


Then create the file /your/path/.htpasswd which contains the users that are allowed to login and their passwords. We do that with thehtpasswd command:
 
htpasswd -c /path/to/your/.htpasswd user1


The -c flag is used only when you are creating a new file. After the first time, you will omit the -c flag, when you are adding new users to an already-existing password file. Otherwise you will overwrite the file!!
Nevertheless, you should store the file in as secure a location as possible, with whatever minimum permissions on the file so that the web server itself can read the file.
Finally we need to add the following lines to /etc/apache2/apache2.conf:
 
<Directory /your/path>
AllowOverride All
</Directory>


You have to adjust /your/path/.htpasswd
Restart your webserver:
 
sudo /etc/init.d/apache2 restart

Troubleshooting


If you can't access your stuff and the dialog keeps popping up, check that you entered the username and password correctly. If it still doesn't work, check the path to your .htpasswd and make sure the path specified in the AuthUserFile directive is correct. Also make sure that both the.htpasswd and .htaccess files are readable by the web server user chmod 644 should do the trick!

Example


Here is an example on how to prevent users from access the directory, password-protect a specific file and allow userse to view a specific file:
AuthUserFile /your/path/.htpasswd
AuthName "Authorization Required"
AuthType Basic
Order Allow,Deny
<Files myfile1.html>
 Order Allow,Deny
 require valid-user
</Files>

<Files myfile2.html>
 Order Deny,Allow
</Files>

Redirect requests using .htaccess and mod_rewrite


  1. Make sure Apache .htaccess is enabled (by default it is enabled in Ubuntu)
  2. Make sure the Apache module mod_rewrite is enabled. Execute:
sudo a2enmod rewrite

..and see if rewrite is listed here:
sudo apache2ctl -M

and then you can redirect requests using RewriteRules. Example:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?_REQUEST=$1 [L]

If you are running windows as your server, create a file .htpasswd at any location with the content.
pritom:pritom
ajay:ajay

No comments:

Post a Comment