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?

1 Answer 1


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.

For example:

<FilesMatch "^(?!(foo|bar|baz)\.php$).+$">
Require all denied

All files, except for foo.php, bar.php and 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
  • Is it possible to make a few exceptions to the rule?
    – posfan12
    Commented Nov 9, 2019 at 17:50
  • 1
    Yes, what kind of exceptions? Certain files? Certain clients? Time of day? - Depending on the type of exception required you may need to change how you are blocking access. (But why do you need an "exception" for something that should only ever be accessed server-side?)
    – MrWhite
    Commented Nov 9, 2019 at 17:58
  • There are a handful of files that I may want people to access, not sure yet. Thanks.
    – posfan12
    Commented Nov 9, 2019 at 18:09
  • 1
    In that case you can use a <FilesMatch> container with a negative lookahead assertion. I've updated my answer.
    – MrWhite
    Commented Nov 9, 2019 at 18:45
  • 1
    I've updated my answer for Apache 2.2. (FYI Apache 2.2 reached end-of-life at the end of 2017. Further, version 2.2.23 was released in June 2012. The latest version on the 2.2 branch is version 2.2.34 which was released July 2017.)
    – MrWhite
    Commented Nov 9, 2019 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.