I have a number of PHP scripts that are meant to be included into other PHP scripts, but otherwise should not be directly accessible to anyone via a Web browser. How do I block people from accessing these files directly over the Internet? Is this possible using htaccess? Would it be better to put all these scripts into a sub-folder first? Also, what is the correct HTTP error/status code to display to visitors in this case?
Would it be better to put all these scripts into a sub-folder first?
Yes. Then create a
.htaccess file in that subdirectory with the following (mod_authz_core) directive:
Require all denied
(Assumes Apache 2.4+)
This will return a 403 Forbidden response for anyone trying to access anything inside that subdirectory.
Even better, put these PHP "includes" outside of the document root and they are inherently protected from direct access without doing anything else.
UPDATE: There are a handful of files that I may want people to access
In that case, you can use negative lookaheads (regex) in a
<FilesMatch> container to create exceptions for the files you wish to allow access.
<FilesMatch "^(?!(foo|bar|baz)\.php$).+$"> Require all denied </FilesMatch>
All files, except for
baz.php will be blocked.
(?!...) is a negative lookahead assertion, so whatever regex is contained in this (ie.
(foo|bar|baz)\.php$) cannot match for the expression as a whole to be successful.
UPDATE#2: Checked my server and Apache Version 2.2.23
If you are still on Apache 2.2 (EOL January 2018) then you will need to change the
Require all denied directive with the following:
Order deny,allow Deny from all