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



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  (or whatever you want) with the following content:

hash=`echo -n "$user:$realm:$pass" | md5sum | cut -b -32`
echo "$user:$realm:$hash"

Make the file executable:

chmod 755 ./

Add A User to the Password File

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

./ 'username' 'myrealm' 'password'

The output will look like this:


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_rewrite",

server.document-root        = "/var/www"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"             = "/var/run/"
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/ " + server.port
include_shell "/usr/share/lighttpd/"
include_shell "/usr/share/lighttpd/"

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.