Apache basic auth for a particular URL

Solution 1:

@Gregg_Leventhal gave me the solution by using environment variables. But the logic I use is the exact inverse of the one used in his answer. For completeness, here is the code to ask authentication only for URL /en :

#set an environtment variable "auth" if the request starts with "/en"
SetEnvIf Request_URI ^/en auth=1

AuthName "Please login to access english part"
AuthType Basic
AuthUserFile "/path/to/my/.htpasswd"

# first, allow everybody
Order Allow,Deny
Satisfy any
Allow from all
Require valid-user
# then, deny only if required
Deny from env=auth

Solution 2:

I see... The code below will disable auth on only the callbacks directory, perhaps you can modify this logic so that it only enables authentication on the desired directory, or disable auth on all dirs whose name doesn't match the one you wish to protect.

# set an environment variable "noauth" if the request starts with "/callbacks/"
SetEnvIf Request_URI ^/callbacks/ noauth=1

# the auth block
AuthName "Please login."
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /xxx/.htpasswd

#Here is where we allow/deny
Order Deny,Allow
Satisfy any
Deny from all
Require valid-user
Allow from env=noauth

Solution 3:

The answers above are suitable for Apache versions prior to 2.4. Here's an update for Apache 2.4 and above, when some of the directives were changed. In this configuration file excerpt, HTTP basic authentication applies to the URI '/members' only. 'joe' refers to a user specified in the file '/home/website/.htpasswd'.

<Directory "/home/website/www">
    AuthType Basic
    AuthName "Members' restricted area"
    AuthBasicProvider file
    AuthUserFile "/home/website/.htpasswd"

    <RequireAny>
        Require expr %{REQUEST_URI} !~ m#^\/members#
        Require user joe
    </RequireAny>
</Directory>