Search code examples
apache.htaccess.htpasswd

How to bypass htpasswd auth on a specific route


mi site has apache authorization but I need to allow access to a certain url request. This url request does not represent an existing file or directory.

This is my .htaccess:

First i tried this approach:

AuthName "Required login"
AuthType Basic
AuthUserFile C:\path\to\apache\.htpasswd
Require expr %{REQUEST_URI} =~ ^specialUrl$
Require valid-user

This gives me an internal server error 500

I've tried:

%{REQUEST_URI} == ^specialUrl$
"%{REQUEST_URI} =~ ^specialUrl$"

I'm not sure how the expression is supposed to be evaluated. I guess i have a syntax error.

Second approach:

As i've seen on this other answer I tried setting an env variable

## Grant access to webhook uri
SetEnvIf Request_URI ^/specialUri noauth=1

## Auth config
AuthName "Required login"
AuthType Basic
AuthUserFile C:\path\to\apache\.htpasswd
Require valid-user

## Allow Deny
Order Deny,Allow
Satisfy any
Deny from all
Allow from env=noauth

This resulted on a 401 error Authentication Required when I POST from a http client.

Authentication required!

This server could not verify that you are authorized to access the URL "/specialUri". You either supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

In case you are allowed to request the document, please check your user-id and password and try again.

.htaccess file:

## Grant access to webhook uri
SetEnvIf Request_URI "\specialUri" noauth

## Auth config
AuthName "Required login"
AuthType Basic
AuthUserFile C:\path\to\.htpasswd

## Allow Deny
Order Deny,Allow
Satisfy any
Deny from all
Require valid-user
Allow from env=noauth


<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
</IfModule>

Solution

  • I don't really understand why but it seemed that there was a redirection on my site. This was fixed adding another allow directive:

    AuthType Basic
    AuthName "Required login"
    AuthUserFile C:\path\to\.htpasswd
    Require valid-user
    SetEnvIf Request_URI "mySpecialUri$" allow
    Order deny,allow
    Deny from all
    Allow from env=webhook
    Allow from env=REDIRECT_noauth
    Allow from 127.0.0.1
    Satisfy any
    

    Note that SetEnvIf Request_URI "mySpecialUri$" is using the latest part of the uri. This is because the redirection I mentioned was generating a longer uri.

    The Allow from env=REDIRECT_noauth fixed the problem