0

I have files with the same name in different directories on the serves (example: stats.php), and I want to password protect some of them (.htaccess file in the root directory). I tried "FilesMatch" with a path to the file and it didn't work, and I tried adding "Directory" path as follows, same problem.

<Directory /var/www/vhosts/folder/httpdocs/directory/>
<FilesMatch "stats.php">
AuthName "Private file"
AuthType Basic
AuthUserFile /var/www/whatever/.htpasswd
require valid-user
</FilesMatch>
</Directory>
Mike
  • 143
  • 1
  • 3

2 Answers2

1

A single .htaccess file in the root directory doesn't work for this purpose. You must place a new .htaccess file to every directory where you need divergent settings from its parent(s):

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

The <Directory> Directive is only allowed in server config and virtual host contexts. The .htaccess file is its equivalent placed directly to the directory. You have two options:

  • Create /var/www/vhosts/folder/httpdocs/directory/.htaccess with the <FilesMatch "stats.php">. This is the only method if you don't have access to the server configuration.
  • Place the <Directory /var/www/vhosts/folder/httpdocs/directory/> in server config or in virtual host. This is better in performance as it's loaded once when Apache starts, rather than on every request.
Esa Jokinen
  • 43,252
  • 2
  • 75
  • 122
0

If you are using Apache 2.4 you can use an If Directive that matches against the request to determine if authorization should be required or not as follows:

<If "%{REQUEST_URI} =~ /stats.php$/">
    AuthName "Private file"
    AuthType Basic
    AuthUserFile /var/www/whatever/.htpasswd
    Require valid-user
    ErrorDocument 401 "Authorization Required"
</If>
PeterA
  • 171
  • 5