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> 

2 Answers 2

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.
2
  • You say: Place the <Directory /var/www/vhosts/folder/httpdocs/directory/> in server config. Just this line? for each directory that has .htaccess? Commented Dec 7, 2018 at 14:03
  • No, the whole block. Only IF you use it instead of the .htaccess approach. Commented Dec 7, 2018 at 14:41
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> 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.