Password-protect A lighttpd Web Server on a Raspberry Pi Using mod_auth

Resources

Walkthrough

Set Up A lighttpd Web Server on the Raspberry Pi

If you haven’t already, set up a Web Server on the Raspberry Pi.

Create A Password File

This file can go anywhere, but for simplicity in this walkthrough, we’ll store it in /etc/lighttpd/.htpasswd .

Create the hideen .htpasswd  directory:

sudo mkdir /etc/lighttpd/.htpasswd

Next, create a script that will hash a user’s password and put everything in the right format for the file.  Make a new file called hash.sh  (or whatever you want) with the following content:

#!/bin/sh
user=$1
realm=$2
pass=$3
hash=`echo -n "$user:$realm:$pass" | md5sum | cut -b -32`
echo "$user:$realm:$hash"

Make the file executable:

chmod 755 ./hash.sh

Add A User to the Password File

Run the script with three arguments: a user, a realm, and a password (which will get hashed).

./hash.sh 'username' 'myrealm' 'password'

The output will look like this:

username:myrealm:<long_string_of_numbers_and_letters>

Create the the password file and paste in the output of the command above:

sudo nano /etc/lighttpd/.htpasswd/lighttpd-htdigest.user

Enable mod_auth

Add the following to the /etc/lighttpd/lighttpd.conf  (highlighted lines).  The directory you want to password protect will go on this line: auth.require = ( “/Directory/To/Protect/” =>

server.modules = (
	"mod_access",
	"mod_alias",
	"mod_compress",
        "mod_redirect",
	"mod_auth",
#       "mod_rewrite",
)

server.document-root        = "/var/www"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"
server.port                 = 80


index-file.names            = ( "index.php", "index.html", "index.lighttpd.html" )
url.access-deny             = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/javascript", "text/css", "text/html", "text/plain" )

# default listening port for IPv6 falls back to the IPv4 port
include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"

auth.backend = "htdigest"                                                          
auth.backend.htdigest.userfile = "/etc/lighttpd/.htpasswd/lighttpd-htdigest.user" 
auth.require = ( "/path/to/protect/" =>
    (
    "method"  => "digest",
    "realm"   => "myrealm",
    "require" => "valid-user"
    ),
)

Restart the Web Server

Restart lighttpd to apply all the changes:

sudo service lighttpd restart

Your site should now prompt for a password whenever you navigate to the directory you chose to password-protect.