How to use a RELATIVE path with AuthUserFile in htaccess?
I have a .htaccess that uses basic authentication. It seems the path to the .htpasswd file isn't relative to the htaccess file, but instead to the server config.
So even though I have the .htaccess and .htpasswd files in the same directory, this doesn't work:
AuthType Basic
AuthName "Private Login"
AuthUserFile .htpasswd
Require valid-user
However, it does work if I change the AuthUserFile to use the absolute path:
AuthType Basic
AuthName "Private Login"
AuthUserFile "/home/user/public_html/mydir/.htpasswd"
Require valid-user
But I would prefer something more mobile as I use this on multiple sites in different areas. I've searched the web but haven't had any resolution. Is it possible to use relative path or variables like %{DOCUMENT_ROOT}
?
It is not possible to use relative paths for AuthUserFile:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the
ServerRoot
.
You have to accept and work around that limitation.
We're using IfDefine
together with an apache2 command line parameter:
.htaccess
(suitable for both development and live systems):
<IfDefine !development>
AuthType Basic
AuthName "Say the secret word"
AuthUserFile /var/www/hostname/.htpasswd
Require valid-user
</IfDefine>
Development server configuration (Debian)
Append the following to /etc/apache2/envvars
:
export APACHE_ARGUMENTS=-Ddevelopment
Restart your apache afterwards and you'll get a password prompt only when you're not on the development server.
You can of course add another IfDefine for the development server, just copy the block and remove the !
.
For just in case people are looking for solution for this:
<If "req('Host') = 'www.example.com'">
Authtype Basic
AuthName "user and password"
AuthUserFile /var/www/www.example.com/.htpasswd
Require valid-user
</If>