Configuring Apache to look for configuration files (.htpasswd) in DocumentRoot not in ServerRoot

74 views Asked by At

I'm looking for a way to force Apache to look for files relatively to DocumentRoot not to ServerRoot. Now if I create .htaccess as follows:

#Protect Directory
AuthName "Please provide valid username and password"
AuthType Basic
AuthUserFile .htpasswd
Require valid-user

Apache looks for the .htpasswd in:

/opt/homebrew/opt/httpd/.htpasswd

and I would like to look for it in:

/opt/homebrew/var/www/FOLDER/.htpasswd

.htaccess is placed in:

/opt/homebrew/var/www/FOLDER/.htaccess

I don't want to change ServerRoot and move all the configuration.

1

There are 1 answers

0
MrWhite On

You cannot change this behaviour. As per the Apache docs for the AuthUserFile directive, the file-path given to the AuthUserFile directive must be either:

  • An absolute filesystem path. For example:

    AuthUserFile /opt/homebrew/var/www/FOLDER/.htpasswd
    

OR,

However, assigning a path relative to the document root would also go against security recommendations, that specifically states:

Make sure that the AuthUserFile is stored outside the document tree of the web-server. Do not put it in the directory that it protects. Otherwise, clients may be able to download the AuthUserFile.

In your example (AuthUserFile .htpasswd) it looks like you are wanting this to be relative to the directory that contains the .htaccess file, not just the document root?


If you need to serve different configs on different servers then you can use <If> expressions (or other conditionals) to set AuthUserFile conditionally based on elements of the request or server.

You could also use defined variables. For example:

# In the server config
Define DOCUMENT_ROOT /opt/homebrew/var/www

In .htaccess:

:
AuthUserFile ${DOCUMENT_ROOT}/FOLDER/.htpasswd