JWest
JWest

Reputation: 55

.htaccess AuthType Basic FilesMatch all but maintenance.html for 401 and 403

We are doing some major work on our site and we want to restrict access to all files except a maintenance page. We want all users to be directed to that page if the cancel or fail the authorization request.

    ErrorDocument 401 /home/user/public_html/maintenance.html
    ErrorDocument 403 /home/user/public_html/maintenance.html
    <FilesMatch ^>
    AuthName "Authorized Only"
    AuthType Basic
    AuthUserFile .htpasswd
    require valid-user
    </FilesMatch>
    <Files "/home/user/public_html/maintenance.html">
        Allow from all
    </Files>

This code doesn't seem to work, users are sent to a page saying:

    Unauthorized

    This server could not verify that you are authorized to access the document requested. 
    Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't 
    understand how to supply the credentials required.
    
    Additionally, a 401 Unauthorized error was encountered while trying to use an ErrorDocument 
    to handle the request.

Upvotes: 2

Views: 191

Answers (1)

MrWhite
MrWhite

Reputation: 45829

There are a number of issues with the code you posted:

<Files "/home/user/public_html/maintenance.html">

The <Files> directive matches file basenames only, not the entire filesystem path. eg. just maintenance.html. So, the above will never be successful.

ErrorDocument 401 /home/user/public_html/maintenance.html

The ErrorDocument takes a root-relative URL-path, not an absolute filesystem path. eg. /maintenance.html.

AuthUserFile .htpasswd

However, the argument to the AuthUserFile directives should be an absolute filesystem path, not a relative path as given above. (A relative path is technically valid, but it's relative to the ServerRoot and you probably don't have access to put files directly in the server root! That's the ServerRoot as defined in the Apache config, not the root directory of your server.)


Solution

Instead of using a separate <Files> container to "allow" access, you can use a negative lookahead to exclude that particular file from triggering the password prompt.

For example:

ErrorDocument 401 /maintenance.html

<FilesMatch "^(?!maintenance\.html$).*">
    AuthName "Authorized Only"
    AuthType Basic
    AuthUserFile /absolute/filesystem/path/to/.htpasswd
    Require valid-user
</FilesMatch>

Upvotes: 2

Related Questions