How to configure basic authentication in Apache httpd virtual hosts?

Solution 1:

You should place this inside a Location directive:

<VirtualHost *:8080>

<Location /> #the / has to be there, otherwise Apache startup fails
            Deny from all
            #Allow from (You may set IP here / to access without password)
            AuthUserFile /usr/local/etc/httpd/users
            AuthName authorization
            AuthType Basic
            Satisfy Any # (or all, if IPs specified and require IP + pass)
                        # any means neither ip nor pass
            require valid-user
</Location>
...
</VirtualHost>

Solution 2:

I am running Apache2 on ubuntu 10.04 — same problem and thanks for the solution. I found that I had to put the configuration in /etc/apache2/apache2.conf

You can generate the username and password using htpasswd. New file:

$ htpasswd -c /srv/auth/.htpasswd squire

To append to existing file:

$ htpasswd -b /srv/auth/.htpasswd squire2 tickleme2

Solution 3:

You can protect a Location or a Directory. For a Directory add something like:

<Directory /some/dir/cgi-bin/>
    Options +ExecCGI
    AddHandler cgi-script .cgi
    AuthType Basic
    AuthName 'Private scripts'
    AuthUserFile '/some/other/dir/.htpasswd'
    Require valid-user
</Directory>

You can also add Deny and Allow directives for a finer control.


Solution 4:

It sounds like you're specifying the authentication settings within the VirtualHost. Typically, these settings are specified under the Directory directive.

You could also use .htaccesss files, but specifying in the Apache conf is a good default, as it has less exposure.

Apache Documentation


Solution 5:

I'm running Apache2 on ubuntu 10.10. I've been having problems with all the solutions above, but this worked well (from apache docs):

<Directory /var/www/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  AuthType Basic
  AuthName "Restricted"
  AuthBasicProvider file
  AuthUserFile /etc/users
  Require user visitor
</Directory>

The biggest difference from the answers above seems to be the AuthBasicProvider directive set to "file" and the Require directive including the "user" bit before the actual username.

Hope this helps someone.