KrzysDan KrzysDan - 1 month ago 28
Apache Configuration Question

htaccess exclude one url from Basic Auth

I need to exclude one Url (or even better one prefix) from normal htaccess Basic Auth protection. Something like /callbacks/myBank or /callbacks/.*
Do you have any hints how to do it?

What I'm not looking for is how to exclude a file.
This has to be url (as this is solution based on PHP framework, and all urls are redirected with mod_rewrite to index.php). So there is no file under this url. Nothing.

Some of those urls are just callbacks from other services (No IP is not known so I cannot exclude based on IP) and they cannot prompt for User / Password.

Current definition is as simple as:

AuthName "Please login."
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /xxx/.htpasswd
require valid-user

Answer

If you are using Apache 2.4, SetEnvIf and mod_rewrite workarounds are no longer necessary since the Require directive is able to interpret expressions directly:

AuthType Basic
AuthName "Please login."
AuthUserFile "/xxx/.htpasswd"

Require expr %{REQUEST_URI} =~ m#^/callbacks/.*#
Require valid-user

Apache 2.4 treats Require directives that are not grouped by <RequireAll> as if they were in a <RequireAny>, which behaves as an "or" statement. Here's a more complicated example that demonstrates matching both the request URI and the query string together, and falling back on requiring a valid user:

AuthType Basic
AuthName "Please login."
AuthUserFile "/xxx/.htpasswd"

<RequireAny>
    <RequireAll>
        # I'm using the alternate matching form here so I don't have
        # to escape the /'s in the URL.
        Require expr %{REQUEST_URI} =~ m#^/callbacks/.*#

        # You can also match on the query string, which is more
        # convenient than SetEnvIf.
        #Require expr %{QUERY_STRING} = 'secret_var=42'
    </RequireAll>

    Require valid-user
</RequireAny>

This example would allow access to /callbacks/foo?secret_var=42 but require a username and password for /callbacks/foo.

Remember that unless you use <RequireAll>, Apache will attempt to match each Require in order so think about which conditions you want to allow first.

The reference for the Require directive is here: https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require

And the expression reference is here: https://httpd.apache.org/docs/2.4/expr.html

Comments