Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require valid user in Apache 2.2 to 2.4

I have the following config in my .htaccess file, which is working in Apache 2.2, but not in 2.4:

SetEnvIf Request_URI ^/admin require_auth=true

AuthUserFile /var/www/site.htpasswd
AuthName "Admin Access"
AuthType Basic

Require all denied
Satisfy any
Require valid-user
Allow from env=!require_auth

How do I convert this to work in Apache 2.4? Basically, if the URI starts with /admin, then they should be asked for the password.

like image 805
Ben Holness Avatar asked Dec 14 '25 17:12

Ben Holness


2 Answers

Just put this .htaccess file in the folder you want to protect:

AuthUserFile /var/www/site/.htpasswd
AuthName "Admin Access"
AuthType Basic
require valid-user

From https://httpd.apache.org/docs/2.4/howto/auth.html

For example, if you wish to protect the directory /usr/local/apache/htdocs/secret, you can use the following directives, either placed in the file /usr/local/apache/htdocs/secret/.htaccess, or placed in httpd.conf inside a <Directory "/usr/local/apache/htdocs/secret"> section.

But with the new If directive we could do it from the root directory as well:

<If "'%{REQUEST_URI}' =~ m#/?admin(/.*)?#">
    AuthUserFile /var/www/site/.htpasswd
    AuthName "Admin Access"
    AuthType Basic
    require valid-user
</If>

I tested this positive on a Ubuntu 16.04.03 LTS Server with Apache 2.4.27.

like image 95
Webdesigner Avatar answered Dec 16 '25 23:12

Webdesigner


You must use the full path to your .htpasswd file.

I will show you the easiest way to get this path.

Create a .php file in the same folder, containing the following code :

<?php
echo dirname(__FILE__) . '/.htpasswd';
?>

Then access it via your browser and it should display the full path you'll need to put in your .htaccess file.

like image 27
Tran Quoc Bao Avatar answered Dec 16 '25 22:12

Tran Quoc Bao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!