f4ssb3nd3r
f4ssb3nd3r

Reputation: 43

Protect directory setting it from root .htaccess

Can I configure the root .htaccess in my host to protect directories instead of put each individual configuration on each directory?

Like this:

/.htaccess (configuring authentication to /folder) /.htpasswd /folder

Instead of in each folder:

/folder /folder/.htaccess /folder/.htpasswd

Upvotes: 1

Views: 799

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

No you can't.

.htaccess files are inherently per directory configuration. That means having an htaccess file inside the /test/ directory, is the same as having the same configuration directives like this in the server/vhost config:

<Directory "/var/www/document-root/test"> 
  ... stuff from htaccess file
</Directory>

because of that, you can't use the <Directory> container in an htaccess file. If you want to do what I think you're trying to do, have all the config either in the server/vhost config inside individual <Directory> containers, or have an htaccess file inside every directory you want to protect.

The other way around this, is if you have a single realm and password file, and you only want it to apply to specific URI's. Then you can use setenvif and something like this:

# set SECURED var to 1 if URI is a protected one
SetEnvIfNoCase Request_URI "^/test/" SECURED=1
SetEnvIfNoCase Request_URI "^/test2/" SECURED=1

# enforce auth if SECURED=1
#AuthType Basic
AuthName "Acesso Restrito"
AuthUserFile /home/public_html/.htpasswd
Require valid-user
Order allow,deny
Allow from all
Deny from env=SECURED
Satisfy any

So the SetEnvIfNoCase directives match the request URI and if it matches one in the list, it requires password auth.

Also, you probably don't want your htpasswd file inside your document root.

Upvotes: 1

Related Questions