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

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.

1 Answer 1


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

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)
  • 3
    WTF is the downvote for? Unless the answer is wrong it should not be downvoted.
    – MrWhite
    Commented Jun 11 at 19:26
  • 2
    And the answer is a good one! Commented Jun 11 at 20:24
  • 1
    It's a good answer, no idea why the -1... you have +1 from me!
    – sotirov
    Commented Jun 11 at 23:41
  • 1
    Thank You - this worked - Im on Ubuntu 22.04 so yes Apache 2.4+
    – anjanesh
    Commented Jun 12 at 1:27
  • 1
    @MrWhite An answer gets downvoted because (someone thinks) it's not useful. Being wrong is one way for an answer not to be useful, but also it could be poorly explained or unclear, or misleading, or include too much irrelevant information, or any of various other reasons that might apply even though it's technically not wrong. Aside from that, it's a fact of life that sometimes people downvote for less legitimate reasons: maybe they think you downvoted their post, or they think the question is bad and you shouldn't have answered it, or they have a competing answer, or so on.
    – David Z
    Commented Jun 12 at 4:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .