5

I have in my /home/sammy/public_html/cache/.htaccess

Options +Indexes

<Files *> AuthType Basic AuthName "Authentication Required" AuthUserFile /home/sammy/public_html/cache/.htpasswd Require valid-user </Files>

But I only want the directory listing password protected - not the file itself.

Issue is, when I go to example.test/cache/somefile.pdf it’s prompting for the username and password.

MrWhite
  • 298
anjanesh
  • 703

1 Answers1

9

If you are using Apache 2.4 (which I expect you are) then you can use an Apache expression in an <If> construct that targets the directory only.

For example:

<If "%{REQUEST_URI} =~ m#/$#">
AuthType Basic
AuthName "Authentication Required"
AuthUserFile /home/sammy/public_html/cache/.htpasswd
Require valid-user
</If>

This uses the regex /$ (using the alternative regex syntax m#<regex>#) to target any URL that ends in a slash. In other words, the directory itself, since this should be the only URL that ends in a slash.

NB: It's not recommended to store the password file in the public HTML space, let alone in the directory it is being used to protect.

Alternatively, (on Apache 2.2) you could also use a regex / negative-lookahead in a <FilesMatch ""> (or <Files ~ "">) container that targets everything that is not a filename of any length (in other words, the directory). For example:

<FilesMatch "^(?!.+)$">
# (Basic auth directives as above)
</FilesMatch>
MrWhite
  • 298