Managing Users To use user authentication, you’ll need to edit and manage user files and group files

Managing Users To use user authentication, you’ll need to edit and manage user files and group files

.


Using htpasswd to manage user files

To deal with user files, we provide a program in the support directory of the distribution called htpasswd. Usage:

htpasswd [-c] file user

The -c, if present, tells htpasswd to create a new passwd file of the specified name instead of editing an old one. file is the pathname of the user file you wish to edit. The user parameter is the name of the user you wish to add or edit.

If htpasswd finds the user you specified, it will ask you to change the user’s password. Type the new password (it will ask twice). HTTPd will then update the file.

If htpasswd doesn’t find the specified user, it will ask you to give the user an initial password.


Group files

The format of the group file is as follows:

groupname: member1 member2 ...

Or, each line contains the name of a group, and a list of members separated by spaces.



<Directory /u/Web>

Options All

<Limit GET>
order allow,deny
allow from all
</Limit>

</Directory>

<Directory /u/Web/docs/info>
AuthType Basic
AuthUserFile /usr/local/etc/httpd/conf/.htpasswd
AuthGroupFile /usr/local/etc/httpd/conf/.htgroup
</Directory>

<Directory /u/Web/docs/info/ncsaonly>
<Limit GET>
order deny,allow
deny from all
allow from .ncsa.uiuc.edu
</Limit>
</Directory>

<Directory /u/Web/docs/info/nonncsa>
<Limit GET>
order allow,deny
allow from all
deny from .ncsa.uiuc.edu
</Limit>
</Directory>

<Directory /u/Web/docs/info/carlosonly>
AuthName Carlos Gold Info
<Limit GET>
require user cvarela
</Limit>
</Directory>

<Directory /u/Web/docs/info/xmosdonly>
AuthName The X Club
<Limit GET>
require group mosaic-x-dev
</Limit>
</Directory>

<Directory /u/Web/docs/info/carlos-and-void>
AuthName Carlos Gold Info
<Limit GET>
order deny,allow
deny from all
allow from void.ncsa.uiuc.edu
require user cvarela
</Limit>
</Directory>

<Directory /u/Web/docs/info/carlos-or-void>
AuthName Carlos Gold Info
<Limit GET>
order mutual-failure
deny from all
allow from void.ncsa.uiuc.edu
require user cvarela
</Limit>
</Directory>

Perl CGI Script to manage multiple usernames/passwords

NOTE: Not Freeware.

.htaccess manager : New Version 3.3

This is a perl CGI script used to manage multiple usernames/passwords for .htaccess/.htpasswd directory protection. This works on most web sites and can be used to handle many password protected folders. In addition to storing the username and encrypted password, you may add additional info for your members such as name, e-mail and comments to help you manage who has access to your “members only” web site. New features include setting an expiration date for a user, keyword search of your members’ list and batch removal of users.

FEATURES

Adding a New user

The “Add User” function is the first that appears after logging into the script. You just need to supply a username and password then click “Add User”. All the other fields are optional. Even the password field can be left blank and the program will pick one at random. You can also supply the member’s name, e-mail address and a short comments field. If you check the box “Check to email new entry to user”, this will tell the program to send out an email with pre-configured text welcoming the user as a new member to your password protected area. If you do check this box, then you can also provide additional text in the large “Extra E-mail Text” box which will be passed along in the email sent out.

You can now add an expiration date for the user, enter it in the format YYYYMMDD (20030631 for example). The script does not automatically delete users but you have the option of sorting your user list by expiration date. This field is optional and you do not have to enter an expiration date.

View, Modify and Delete Users

The “List User” screen does three things, it provides a list of all your members, allows you to delete a member and modify any information for a particular member. The user list shows “Username – Member Name – Email address – comments”. You can easily control the size of this box by changing the scrollsize option in the program settings. To delete a user all you have to do is highlight then click the delete button. To Modify a user, you also highlight the record then you can modify the password, name, email and comments field. You can even check the box to resend their confirmation email. If one of your members forgets their password, you just come to this screen, highlight them, enter a new password, check the “e-mail” box and click “Modify User”.

Sort By Expiration : Will sort all of your members by expiration date in ascending order.
Sort by username : Sorts the list by username (the default view)
Keyword Search : Will search the username, name, email, comments and expiration field for whatever you type in

Change Directory

“Change Protected Directory” screen allows you to manage password protection on another folder. This also makes it easier than going back to the login screen. This screen displays the path you have setup where your password protected directories will be located. You just type in the new folder name and click “Change Directory”. This way you can use the script to manage as many password protected folders as you like. If you are protecting a folder within another folder then you type in for example : member_area/secure1 and then the script will manage the “secure1″ folder located in the “member_area” folder. You will also find two additional buttons on this screen. One is to view the .htaccess file and the other for the .htpasswd file. This is a good thing to do every now and then so you can make backups of your member database.

Generate .htaccess File

When you first setup password protection on a folder, you need to create a .htaccess file inside it. You can either do this manually or have the script create this file for you. You do not need to do this every time you add a user. Once a .htaccess file has been created in a folder, you don’t need to run this function again. The Directory field will display the folder name you are about to generate a .htaccess file for. The Realm is for the message that will be displayed in the pop-up box that appears when a user tries to login to your secure area. If you want the script to create the file, then check the “Create .htaccess file on Server”. As for the format you want, the majority of unix servers use “.htaccess file for apache” Some web hosting companies use Cobalt RAQ or Zeus.

Password Retrieval (Version 3.2+)

You can now have your members generate new passwords for themselves if they forget their login information. To activate this feature in the script, send your users to :

http://www.yourdomain.com/admin.cgi?action=F&targetdir=dirname

Where “dirname” is the name of the directory you are protecting (same directory you type in when accessing admin.cgi)
If a member forgets their username, they just type in their email address and it will be sent to them. If they forget their password, they just type in their e-mail and username then a new password will be generated.

Version 3.3 just added the option for users to select their own new password if they supply their username and their old password.

Extract E-mails

Extract E-mails allows you to export a list of all your members’ email addresses. The list will be formatted one email address per line. Some email programs require that each address have a comma after it which you can select when exporting. The addresses will appear on the next page which you can then copy/paste into Eudora/Outlook etc.

Mass E-mails (Version 3.2+)

Allows you to send a broadcast email message to all members. E-mails can be configured to send specific information about each user using the %tag%.
Example : Hello %name%,
Your userid is : %username%
Your email is : %email%
Your account expires on : %expiration%
Comments about your account : %comments%

Manual Import

If you have a large list of usernames that you want to add as members in just one click then the Manual Import feature will handle this. All you do is copy/paste or type the list into the large text box. Here is a sample of what the list would look like :
username,password
joe,joe123
jack,jack887
jane,janepass

You can also import the additional fields :
username, password, name, email, comments, expiration
joe,joe123,Joe Smith,joe@smith.com,friend
jack,jack887,Jack Smith,jack@smith.com,

Also, you can even leave the password field blank to have the script automatically generate it for you :
joe,,Joe Smith,joe@smith.com
jack,,Jack Smith,jack@smith.com
(note the two commas after eachother)

You can also automatically send an email to each member that you import by checking the “Send E-mail” box. Even the comments field can be sent if you wish.
Whenever you run the import, the script will always check to make sure that the username doesn’t already exits. If any username in your list exists, no records will be imported.

Import From File

The import from file feature is if you have a list of members too large to fit in the manual import box or maybe you have another program that exports the list of usernames/passwords to a file that need to be imported later. By default, the name of the file that the program looks for is called htimport.txt and will be located in the directory you are protecting. The format for records to be imported is the same as the manual import :
username,password
or
username,password,name,email,comments, expiration
or
username,,name,email,comments

Whenever you run the import, the script will always check to make sure that the username doesn’t already exits. If any username in your list exists, no records will be imported.

Change Program Settings

This screen allows you to update configurations in the program without having to manually edit the admin.cgi script. The settings you can change are :
Base directory : The physical server path to where your protected folder or folders are located. (Not to be confused with the URL or domain name to your web site). example : /www/yourdomain/htdocs/

Password : The master password to access the admin.cgi script with.
Sendmail : The path to sendmail for your server.
Scroll Size : The number of members that will be displayed in the “List Users” screen before it scrolls.
Email From : Your e-mail address goes here. This is also the address used when sending email confirmations to your new members, they will see this in the From field. You can also add your name in parenthesis : joe@smith.com (Joe Smith)
Email Subject : The subject of the emails which are sent out to new members.
Top of Email : The text that will appear in the email sent to users. After this text will come the username and password.
Bottom of Email : The text that will appear after the username/password and the end of the email.
The data for all these variables is stored in a file called adminvars.cgi
You do not need to create this file on the server. If the file is not there it will be created with default settings. If for some reason your script does not have permission to create the file, you may need to upload a blank one and chmod it to 777. The default admin password is test.

FAQ

  • Does my server support .htaccess ?
    In the majority of cases, if it’s unix and runs the apache server then yes. The best way to find out is by uploading a .htaccess file to a subdirectory on your server then access it with your browser and see if it asks you for a login.

    • Here’s one you can use on your site : .htaccess upload this file to a directory on your server (in ASCII mode), example : yourdomain.com/members/ then rename it to .htaccess (yes, that’s a period infront of “htaccess”)
    • Then using your browser, go to http://www.yourdomain.com/members/ If you’re prompted to enter a username and password, then it will work!
  • After a member enters their username/password to the protected directory, do they need to re-enter it each time they access a new file ?
    No, the way .htaccess works, is it protects all files in the directory it is in. So once a user is authenticated, they have access to everything in that folder. But if a user bookmarks a page in the secure area, they will be required to re-enter the user/pass if they shut down their web browser and restart.
  • Can I protect multiple directories with the same list of users ?
    Yes, in this case, you would have the admin.cgi script only manage one of the directories for you, then all you would need to do is copy the same .htaccess file over to the new directory you want to protect. If you look in the .htaccess file, it says right there the full path to the .htpasswd file it will look for to authenticate users AuthUserFile /home/secure/.htpasswd.
  • Can I protect multiple directories with a different list of users ?
    Yes, in this case, you just run the admin.cgi script and tell it to refresh to a new directory to access that list of users. By doing this, each directory will have its own .htpasswd and .htaccess file.
  • Will this work with Frontpage Extensions ?
    Yes, 90% of the time it will. Just as long as the directory you are protecting is setup as a regular directory in frontpage and not a “subweb”. The idea is to tell Frontpage not to overwrite the .htaccess file that admin.cgi creates
  • Can the script automatically send passwords to users who forget their login ?
    Yes, this feature is available as of version 3.2. Just provide a link for your members to admin.cgi?action=F&targetdir=dirname. They just have to supply their e-mail address and username then the script will generate a new password and e-mail it to them.
  • How do I configure the e-mail that is sent to members ?
    When you add a new user, you have the option of sending them an e-mail with their new username/password (saves you the time of having to do it manually each time). You can configure the subject of the emails, the sender’s name and e-mail address (you) and the text in the body of the email. These settings can be changed by logging into admin.cgi and scrolling down to the section labeled “Change Program Settings”. You can read about this in the Features page.
  • How do I add a long list of users at once (instead of adding them one at a time) ?
    This is what the Manual Import feature does. After running the script, scroll down to “Manual Import” and you’ll see a large TEXT box, this is where you can copy/paste your list of users. See the Features page.
  • Will this script work on NT server ?
    No.
  • I don’t know anything about CGI, chmod etc. can I still use it ?
    Not a problem, we’ll install the script for you. When you place your order, be sure to provide your URL (http://….) ftp username and password. Almost all installs are completed the same day you place your order.
  • What if the program does not run on my server, is there a refund ?
    We will not charge your credit card until the program works successfully on your web hosting account/server. Credit cards are usually processed a few days after you submit your order.
  • File Permission Security on Shared Web Hosting

    Some web hosts allows you to create multiple users per account. Each user can have domain assigned to its home home directory accessible via FTP or SSH/SCP. The problem with multiple users on the same account is that they share the same default unix group, and default permissions allow their files to be easily modified by the members of this group. Usually this doesn’t pose a problem as each user is probably trusted by account owner to not to mess with others files, but if one of the users have their web application hacked then all other users on the same account will be in danger.

    By default (on DreamHost) all files in your account are created with 644 privileges and directories are with 775. That means any user can read your files and any user from the same account can move and add files in your freshly made directories. Your home directory is different, though. By default it carries 751 attribute meaning that only members of your group can see your files, but can’t add any new. These group access schemes are possible, because every user in your account has its primary/default group set to “pgxxxxxx”, which is assigned to every new file you create by default. The normal way to secure users from web-intrusion is to assign a separate group to the web-server user, removing it from default group. This way, exploited scripts will not be able to traverse into home directories of other users on your account. To allow account users to update centralized web-site they could be added to web-site group explicitly. But this “normal way” doesn’t work with DreamHost, because you can’t delete web-user from the default group and unless you set access for every new file explicitly, it will be possible for an intruder to read it.

    To make managing privileges easier in interactive sessions “umask 007″ command can be specified in your .bash_profile – this makes all new files carry xx0 mask. You also need to control your scripts (web based or cron/shell) so that they set mask for critical files explicitly. To secure account users from access by means of hacked user script you would also like to define another group for every user in your account and change group ownership of the user’s home directory to that group with “set gid” bit set (and optional umask 007 in .bash_profile).

    1. Add a separate user and group for every domain where apache will be running
    2. Add a separate group for other user accounts
    3. Change the default group for new files created by your users by changing the group of their home directory and setting set gid bit for it (it is impossible to do this with FTP accounts, therefore you will need to login in each account via SSH)
    4. Add users who need access to web-site into the web-user group
    5. Optionally set umask 007 in .bash_profile for every user to tweak default DreamHost 775/664 permissions to something like 770/660 for directories and files that are not meant to be read by Apache (660 could also be used for all web scripts including .php as they are not read by dhapache CGI, but merely executed)

    Apache Security

    All your web files that need to be read by Apache should be readable by everyone as Apache itself is run under dhapache user. However, executable scripts like .php are executed under your own user and do not have to be world readable as they are not actually read by Apache, but executed via suEXEC. Quite the opposite – to prevent your code or database settings from being messed by any third-parties you SHOULD set permissions to these files explicitly to something like 640 or even 600 depending on who do you trust.

    Multiuser security setup example

    For our example, we will create a example_www user and a new_webroot group for serving web files with apache and setup a example user with a ‘rfrc group to manage mail and keep other files on DH privately. Since these records already exist, you will need to subsitute your own names.

    • Login to DreamHost panel and create the users example_www and example with shell access.
    • From groups tab create two groups – new_webroot and rfrc. Note that users created in previous step are still members of the same default pgxxxxxx group.
    • Add example_www to ‘the ‘new_webroot group and example to both the new_webroot and rfrc groups
    • Move your domain to example_www account (mine is example.org)
    • Now login to SSH with your example_www user and change the default group for your home directory with “sgid” bit set to make all current and new files/directories created in this directory have the same new_webroot group.
     $ chgrp -R new_webroot .
     $ chmod 2751 .
     $ chmod 2771 example.org

    By setting 2771 the directory will be writable by the owner, the group and will be only executable by others. The contents of an executable only directory cannot be listed, but the files inside it can be read (if the permissions of the file allow it). It is important that the directory can be executable in order to allow static content (e.g. .html files) inside it to be read. Remember that directories you don’t want anyone to have web access to, should be 0770 (writable by the owner and group, or 0750 writable by the owner and readable by group). Such strict permissions should by applied to password files, php include files or databases files (such as SQLite, BDB, etc).

    • Do the same for example user, but specify rfrc group instead.

    chgrp -R rfrc .
    chmod 2751 .

    • Optionally modify umask in .bash_profile in user’s home to 007 to make all files created by this user have 660 permissions set by default. If you want that newly created files by accessible by the web, you need to manually setup it’s permissions to 664.

    Now I can login as the user “example” and update the web-site in the ../example_www/example.org directory. There is one more setup needed. Because files copied from other accounts can have 644 permissions set instead of 664, you need a script which will update permissions to 664 or 660 to allow other group members modify such files.

    Automatic Post-commit Checkout

    Subversion can be a very useful tool for developing Web sites or Web-based applications. You may wonder, though, how that would work. After you commit your changes to your repository, how do you have them reflected on your site? The easiest method is to have your site’s directory on the server be a working copy checked out from your Subversion repository. If you elect to do this be certain to modify your site’s .htaccess to prevent users from browsing Subversion’s control files. Something simple in the root of your site such as the following will suffice.

    RedirectMatch 403 /\.svn.*$

    Additionally you can configure your site to automatically check out the current sources from your repository by using Subversion’s “hook scripts“. In short, the script called hooks/post-commit will be executed by the web server each time new sources are checked into your repository. Be advised that when the web server executes this script it is running in the security context of the dhapache user — this user does not and should not (for security reasons) have the necessary permissions to modify the files in your web site’s directory. As such we need to arrange for the post-commit script to run the update in the security context of a user with the privileges necessary to update your site.

    Users familiar with UNIX systems will recognize that this is a task for a setuid binary. Unfortunately the DreamHost /home/ directories are NFS filesystems which are, for security reasons, mounted with setuid disabled. Fortunately the workaround is trivial — simply set up your update script as a CGI script and have the Subversion post-commit hook invoke this script. Instructions follow.

    1. Create a private directory on your website to host your updater script such as /home/username/mysite.com/cgi-bin/pri

    1b. And set its permissions so that only the user has write access to it.

    chmod 755 pri

    2. Secure the private directory by creating a .htaccess file with contents similar to the following.

    AuthName "Dialog prompt"
    AuthType Basic
    AuthUserFile /home/username/mysite.com/cgi-bin/pri/.htpasswd
    Require valid-user

    3. Using the htpasswd utility create the .htpasswd file by running the following command in your /home/username/mysite.com/cgi-bin/pri directory. For security reasons make up a new username and password and do not re-use the username and password of a user you have created on your server or a user you have given access to your subversion repository.

    htpasswd -bc .htpasswd someuser somepasswd

    4. Now that you have created and secured a directory for this special CGI script to live in, create a script in that directory called do_update.cgi with the following contents.

    #!/bin/sh
    set -f
    echo "Content-type: text/plain; charset=iso-8859-1"
    echo
    /usr/bin/svn update /home/username/mysite.com

    4b. Don’t forget to give execution privilege to your file. Only the user can have write access to it.

    chmod 755 do_update.cgi

    5. Finally, modify your /home/username/svn/projectname/hooks/post-commit to invoke your CGI script so your site will update after each commit.

    #!/bin/bash
    wget --http-user=someuser --http-passwd=somepasswd -O - http://mysite.com/cgi-bin/pri/do_update.cgi

    5b. Don’t forget to give execution privilege to your file. Again, only the user can have write access to it.

    chmod 755 post-commit

    Blocking Abuse by IP Address

    IP Abuse Detection Script

    This shell script checks the access and error logs generated by apache for a particular domain, looking for the IP addresses that have connected to your site the most. It checks for IP addresses that trigger a Concurrent Connection Limit Exceeded error, which is a good sign they are an automated bot of some kind, making over 20 requests to your site at the same time. This script also checks for Internal Recursion Errors which can have very negative effects on your speed and resources, and are basically internal looping problems generally caused by improperly configured Htaccess setups.

    Once the script finishes scanning your logs for those events, it automatically generates .htaccess code that you may add to your sites root .htaccess file to block those IP addresses the script identified as abusive. The only IP addresses included in the generated .htaccess file are those that have no reverse dns.

    alt text

    Installation

    1. Log in to your account using SSH
    2. Save this code in your $HOME directory as ip-abuse-lookup.sh
      1. Run pico $HOME/ip-abuse-lookup.sh
      2. Copy the code to the screen by clicking the right-mouse-button
      3. Hold down the Ctrl button and then press x to save
    3. Run the command dos2unix -dv $HOME/ip-abuse-lookup.sh to fix line break issues
    4. Run the command chmod -v 744 $HOME/ip-abuse-lookup.sh to make executable

    Running the Script

    From your $HOME directory (cd $HOME), run ./ip-abuse-lookup.sh to execute the program.

    Example Generated .htaccess

    This script will also generate code that you can place in your .htaccess file to block specific abusers.

    ## IP-ABUSE-LOOKUP
    Order Allow,Deny
    Allow from All
    Deny from 6.132.177.129 27.67.117.178 6.135.166.102 8.93.225.133
    Deny from 21.194.136.15 22.120.61.3 6.252.139.246 9.64.50.83
    Deny from 8.123.144.98 21.249.83.87 29.85.238.28 25.214.237.62
    Deny from 22.115.130.23 13.57.156.241 14.121.4.82 6.208.172.177

    ip-abuse-lookup.sh

    #!/bin/sh
    # Version 0.2, 2008-04-20
    
    # User-contributed script. Not sponsored by DreamHost.
    # Script created 2008-01-16 by AskApache 
    
    ### SHELL OPTIONS
    set +o noclobber  # allowed to clobber files
    set +o noglob     # globbing on
    set +o xtrace     # change to - to enable tracing
    set +o verbose    # change to - to enable verbose debugging
    set -e            # abort on first error

    The full script is here, but the authors has an updated Ip Abuse Blocking with .htaccess page.

    Apache mod_auth_digest authentication

    Digest authentication is described in RFC 2617.

    Directives

    # AuthDBGroupFile

    # AuthDBUserFile

    # AuthDBAuthoritative

    # AuthDBMGroupFile

    # AuthDBMUserFile

    # AuthDBMAuthoritative

    # AuthDigestFile

    # AuthDigestGroupFile

    # AuthDigestQop

    # AuthDigestNonceLifetime

    # AuthDigestNonceFormat

    # AuthDigestNcCheck

    # AuthDigestAlgorithm

    # AuthDigestDomain

    # Using Digest Authentication

    Using Digest Authentication

    Using MD5 Digest authentication is very simple. Simply set up authentication normally, using “AuthType Digest” and “AuthDigestFile” instead of the normal “AuthType Basic” and “AuthUserFile”; also, replace any “AuthGroupFile” with “AuthDigestGroupFile”. Then add a “AuthDigestDomain” directive containing at least the root URI(s) for this protection space. Example:

    AuthType Digest
    AuthName "private area"
    AuthDigestDomain /private/ http://mirror.my.dom/private2/
    AuthDigestFile /web/auth/.digest_pw
    Require valid-user

    Note: Digest authentication is more secure than Basic authentication, but only works with supporting browsers. As of September 2004, major browsers that support digest authentication include Amaya, Konqueror, MS Internet Explorer for Mac OS X and Windows (although the Windows version fails when used with a query string — see “Working with MS Internet Explorer” below for a workaround), Mozilla, Netscape 7, Opera, and Safari. lynx does not support digest authentication. Since digest authentication is not as widely implemented as basic authentication, you should use it only in environments where all users will have supporting browsers.

    Apache module mod_auth_digest

    from the article: 5 htaccess Tricks Every Webmaster Should Know

    from the article: 5 htaccess Tricks Every Webmaster Should Know

    If you’re new to htaccess, here’s a quick introduction. Otherwise, here are 5 sets of htaccess directives every webmaster should know:

    1 – Redirect Visitors While You Update Your Site

    Update and test your site while visitors are redirected to the page of your choice:

    order deny,allow
    deny from all
    allow from 123.123.123.123
    
    ErrorDocument 403 /page.html
    
    <Files page.html>
    allow from all
    </Files>

    Replace 123.123.123.123 with your IP address. Also replace page.html with the name of the page you want visitors to see.

    2 – Display a Custom 404 Error Page

    Your server displays a “404 File Not Found” error page whenever a visitor tries to access a page on your site that doesn’t exist.

    You can replace the server’s default error page with one of your own that explains the error in plain language and links visitors to your home page. Here’s how to use your own page:

    ErrorDocument 404 /404.html

    Replace 404.html with the name of the page you want visitors to see.

    3 – Handle Moved or Renamed Pages

    You’ve moved or renamed a page on your site and you want visitors automatically sent to the new page when they try to access the old one. Use a 301 redirect:

    Redirect 301 /old.html http://yoursite.com/new.html

    Using a 301 redirect also ensures the page doesn’t lose its search engine ranking.

    4 – Prevent Directory Browsing

    When there’s no index page in a directory, visitors can look and see what’s inside. Some servers are configured to prevent directory browsing like this. If yours isn’t, here’s how to set it up:

    Options All -Indexes

    5 – Create User Friendly URLs

    Which of the two URLs below looks friendlier?

    http://yoursite.com/about
    http://yoursite.com/pages/about.html

    When it comes to URLs, as long as the meaning is clear, shorter is always better.

    With htaccess and an Apache module called mod_rewrite, you can set up URLs however you want. Your server can show the contents of “/pages/about.html” whenever anyone visits “http://yoursite.com/about”. Here are a few examples:

    RewriteEngine on
    RewriteRule ^about/$    /pages/about.html [L]
    RewriteRule ^features/$ /features.php [L]
    RewriteRule ^buy/$      /buy.html [L]
    RewriteRule ^contact/$  /pages/contact.htm [L]

    There’s a lot more to mod_rewrite and htaccess. Check out the links below for more details and tricks.

    Creating the password file

    Found an older htpasswd tutorial

    Introduction

    You may have visited a web page that pops up a dialog box similar to this one:

    Password protection dialog

    If you don’t know the username and password to enter, then you can’t access the page or site – it’s “password protected”. It’s sometimes handy to be able to password protect your pages like this – for example:

    • You’re building a new site, but you only want yourself (and maybe a select few) to be able to view the work-in-progress.
    • You have an area of your site that you never want the general public to have access to – for example, your web stats or private pages.
    • You have some paid (subscription) content on your site that only subscribers should be able to access.

    Apache lets you password protect individual files, folders, or your entire site fairly easily. Read on to find out how it’s done.

    How it works

    To add password protection to your pages, you need to do the following two things:

    1. Create a text file on your server that will store your username and password.
    2. Create a special file called .htaccess in the folder you want to protect.

    That’s it! Now let’s take a look at how to do each step.

    Creating the password file

    The first step is to create a simple text file that will store your username and password, separated by a colon (:). The small catch is that the password must be encrypted. Luckily, there are many free web-based utilities that will encrypt the password for you. Try one of these:

    • 4WebHelp’s online .htpasswd encryption tool
    • Alterlinks .htaccess password generator
    • htmlite’s htpasswd encryption page

    Simply enter your desired username and password in one of these pages and submit the form. You’ll get back a string similar to the following:

    fred:p29cmnwl4a0et

    Now, open up your favourite text editor (e.g. Notepad or TextEdit), then copy and paste the username/password string into the editor. Save the file and call it .htpasswd.

    Next, upload this file to your website. Make sure you place it outside the Web root of your site if possible, as you don’t want just anyone to be able to view the file! For example, place it above your public_html or htdocs folder. (Having said this, Apache is often set up by default to block web-based access to files beginning with .ht. Better safe than sorry though!)

    If you can’t place your .htpasswd file outside your Web root, name it something that’s not easily guessable – for example, .raxuymwp – so that people won’t be able to find it easily.

    Alternative: Creating the password file using htpasswd

    If you have SSH access to your web server (or you’re running Apache on a local machine), you can encrypt your password and add it to your password file in one go by using the htpasswd utility that comes with Apache. Simply SSH to your server or open up a terminal window on your local machine, cd to the folder where you want to create your password file, and type:

    htpasswd -c .htpasswd fred

    (where fred is the username you want to use). You’ll be prompted to enter and retype your password, then the .htpasswd file will be created for you.

    Creating the .htaccess file

    Now that you have created and uploaded your password file, you need to tell Apache to use it to protect your page(s) or site. This is what your .htaccess file will do.

    Open your text editor again, create a new file, and save it as .htaccess.

    Protecting a folder

    To password protect a folder on your site, you need to put the following code in your .htaccess file:

    
    AuthUserFile /full/path/to/.htpasswd
    AuthType Basic
    AuthName "My Secret Folder"
    Require valid-user
    

    /full/path/to/.htpasswd should be the full path to the .htpasswd file that you uploaded earlier. The full path is the path to the file from the Web server’s volume root – for example, /home/username/.htpasswd or C:\wwwroot\username\.htpasswd. (If you’re not sure of the full path to your site or home directory, ask your Web hosting company for this info.)

    The above .htaccess file will password protect all files in the folder that it is placed in, and all sub-folders under that folder too. So if you wanted to password protect your entire site, you would place the .htaccess file in your Web root folder.

    Protecting a file

    To password protect just a single file in a folder, use the following .htaccess file:

    
    AuthUserFile /full/path/to/.htpasswd
    AuthType Basic
    AuthName "My Secret Page"
    
    <Files "mypage.html">
      Require valid-user
    </Files>
    
    

    This will password protect just the mypage.html file in the folder where you put the .htaccess file.

    Uploading the .htaccess file

    Once you’ve created your .htaccess file, upload it to your website, placing it in the folder (or folder containing the file) that you want to protect.

    Testing it out

    Now use your Web browser to visit the folder or file that you’ve protected. You should see a password dialog like the one shown at the start of this tutorial. Type in the username and (unencrypted) password that you chose earlier, and you should be given access to your folder or file!

    (By the way: with this type of password protection, you continue to have access to the password protected stuff until you restart your browser.)

    Problems?

    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 file on the server – 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 for UNIX/Linux/FreeBSD servers).

    If the password protection isn’t working (i.e. you can still access your stuff without needing to enter a username/password), check that you uploaded your .htaccess file to the right folder. Also check that your web server supports .htaccess password protection (it needs to be an Apache server, and your server admin needs to have enabled the AuthConfig override for your site).

    Password protecting more stuff

    • If you want to password protect other folders (that aren’t under the currently protected folder), simply copy your .htaccess file to the new folder to be protected.
    • To password protect more than one file in the same folder, just create more <Files></Files> blocks within the same .htaccess file – for example:
    
    AuthUserFile /full/path/to/.htpasswd
    AuthType Basic
    AuthName "My Secret Page"
    
    <Files "mypage.html">
      Require valid-user
    </Files>
    
    <Files "myotherpage.html">
      Require valid-user
    </Files>
    

    Adding more usernames and passwords

    You’re not restricted to just one username/password. If you want to add other usernames and passwords, simply repeat the “Creating the password file” procedure above, but add each new username/password line to your existing .htpasswd file, e.g.:

    Basics of password protecting a directory

    Here’s the basics of password protecting a directory on your server.

    First, you need to create a password file. Exactly how you do this will vary depending on what authentication provider you have chosen. More on that later. To start with, we’ll use a text password file.

    This file should be placed somewhere not accessible from the web. This is so that folks cannot download the password file. For example, if your documents are served out of /usr/local/apache/htdocs you might want to put the password file(s) in /usr/local/apache/passwd.

    To create the file, use the htpasswd utility that came with Apache. This will be located in the bin directory of wherever you installed Apache. If you have installed Apache from a third-party package, it may be in your execution path.

    To create the file, type:

    htpasswd -c /usr/local/apache/passwd/passwords rbowen

    htpasswd will ask you for the password, and then ask you to type it again to confirm it:

    # htpasswd -c /usr/local/apache/passwd/passwords rbowen
    New password: mypassword
    Re-type new password: mypassword
    Adding password for user rbowen

    If htpasswd is not in your path, of course you’ll have to type the full path to the file to get it to run. With a default installation, it’s located at /usr/local/apache2/bin/htpasswd

    Next, you’ll need to configure the server to request a password and tell the server which users are allowed access. You can do this either by editing the httpd.conf file or using an .htaccess file. For example, if you wish to protect the directory /usr/local/apache/htdocs/secret, you can use the following directives, either placed in the file /usr/local/apache/htdocs/secret/.htaccess, or placed in httpd.conf inside a <Directory /usr/local/apache/apache/htdocs/secret> section.

    AuthType Basic
    AuthName "Restricted Files"
    # (Following line optional)
    AuthBasicProvider file
    AuthUserFile /usr/local/apache/passwd/passwords
    Require user rbowen

    Let’s examine each of those directives individually. The AuthType directive selects that method that is used to authenticate the user. The most common method is Basic, and this is the method implemented by mod_auth_basic. It is important to be aware, however, that Basic authentication sends the password from the client to the server unencrypted. This method should therefore not be used for highly sensitive data, unless accompanied by mod_ssl. Apache supports one other authentication method: AuthType Digest. This method is implemented by mod_auth_digest and is much more secure. Most recent browsers support Digest authentication.

    The AuthName directive sets the Realm to be used in the authentication. The realm serves two major functions. First, the client often presents this information to the user as part of the password dialog box. Second, it is used by the client to determine what password to send for a given authenticated area.

    So, for example, once a client has authenticated in the "Restricted Files" area, it will automatically retry the same password for any area on the same server that is marked with the "Restricted Files" Realm. Therefore, you can prevent a user from being prompted more than once for a password by letting multiple restricted areas share the same realm. Of course, for security reasons, the client will always need to ask again for the password whenever the hostname of the server changes.

    The AuthBasicProvider is, in this case, optional, since file is the default value for this directive. You’ll need to use this directive if you are choosing a different source for authentication, such as mod_authn_dbm or mod_authn_dbd.

    The AuthUserFile directive sets the path to the password file that we just created with htpasswd. If you have a large number of users, it can be quite slow to search through a plain text file to authenticate the user on each request. Apache also has the ability to store user information in fast database files. The mod_authn_dbm module provides the AuthDBMUserFile directive. These files can be created and manipulated with the dbmmanage program. Many other types of authentication options are available from third party modules in the Apache Modules Database.

    Finally, the Require directive provides the authorization part of the process by setting the user that is allowed to access this region of the server. In the next section, we discuss various ways to use the Require directive.

    Letting more than one person in

    The directives above only let one person (specifically someone with a username of rbowen) into the directory. In most cases, you’ll want to let more than one person in. This is where the AuthGroupFile comes in.

    If you want to let more than one person in, you’ll need to create a group file that associates group names with a list of users in that group. The format of this file is pretty simple, and you can create it with your favorite editor. The contents of the file will look like this:

    GroupName: rbowen dpitts sungo rshersey

    That’s just a list of the members of the group in a long line separated by spaces.

    To add a user to your already existing password file, type:

    htpasswd /usr/local/apache/passwd/passwords dpitts

    You’ll get the same response as before, but it will be appended to the existing file, rather than creating a new file. (It’s the -c that makes it create a new password file).

    Now, you need to modify your .htaccess file to look like the following:

    AuthType Basic
    AuthName "By Invitation Only"
    # Optional line:
    AuthBasicProvider file
    AuthUserFile /usr/local/apache/passwd/passwords
    AuthGroupFile /usr/local/apache/passwd/groups
    Require group GroupName

    Now, anyone that is listed in the group GroupName, and has an entry in the password file, will be let in, if they type the correct password.

    There’s another way to let multiple users in that is less specific. Rather than creating a group file, you can just use the following directive:

    Require valid-user

    Using that rather than the Require user rbowen line will allow anyone in that is listed in the password file, and who correctly enters their password. You can even emulate the group behavior here, by just keeping a separate password file for each group. The advantage of this approach is that Apache only has to check one file, rather than two. The disadvantage is that you have to maintain a bunch of password files, and remember to reference the right one in the AuthUserFile directive.

    Because of the way that Basic authentication is specified, your username and password must be verified every time you request a document from the server. This is even if you’re reloading the same page, and for every image on the page (if they come from a protected directory). As you can imagine, this slows things down a little. The amount that it slows things down is proportional to the size of the password file, because it has to open up that file, and go down the list of users until it gets to your name. And it has to do this every time a page is loaded.

    A consequence of this is that there’s a practical limit to how many users you can put in one password file. This limit will vary depending on the performance of your particular server machine, but you can expect to see slowdowns once you get above a few hundred entries, and may wish to consider a different authentication method at that time.

    Alternate password storage

    Because storing passwords in plain text files has the above problems, you may wish to store your passwords somewhere else, such as in a database.

    mod_authn_dbm and mod_authn_dbd are two modules which make this possible. Rather than selecting AuthBasicProvider file, instead you can choose dbm or dbd as your storage format.

    To select a dbd file rather than a text file, for example:

    <Directory /www/docs/private>
    AuthName "Private"
    AuthType Basic
    AuthBasicProvider dbm
    AuthDBMUserFile /www/passwords/passwd.dbm
    Require valid-user </Directory>

    Other options are available. Consult the mod_authn_dbm documentation for more details.

    htpasswd information

    You should also read the documentation for mod_auth_basic and mod_authz_host which contain some more information about how this all works. mod_authn_alias can also help in simplifying certain authentication configurations.

    The various ciphers supported by Apache for authentication data are explained in Password Encryptions.

    And you may want to look at the Access Control howto, which discusses a number of related topics.