Deny direct access to all .php files except index.php


I want to deny direct access to all .php files except one: index.php

The only access to the other .php files should be through php include.

If possible I want all files in the same folder.


A general rule would be nice, so I don't need to go through all files. The risk is that I forget a file or line.


The index.php is in a folder

I want to deny access to all .php files in myfolder and subfolders to that folder.

5/24/2013 2:09:47 PM

Accepted Answer

In index.php, add an access value like this:

$access = 'my_value';

In every other file, include this check before even a single byte is echoed out by php:

if(empty($access)) {

This way, other php files will be accessible only through require / include and not through the url.

12/5/2011 4:56:12 PM

Are you sure, you want to do that? Even css and js files and images and ...?

OK, first check if mod_access in installed to apache, then add the following to your .htaccess:

Order Deny,Allow
Deny from all
Allow from

<Files /index.php>
    Order Allow,Deny
    Allow from all

The first directive forbids access to any files except from localhost, because of Order Deny,Allow, Allow gets applied later, the second directive only affects index.php.

Caveat: No space after the comma in the Order line.

To allow access to files matching *.css or *.js use this directive:

<FilesMatch ".*\.(css|js)$">
    Order Allow,Deny
    Allow from all

You cannot use directives for <Location> or <Directory> inside .htaccess files, though.

Your option would be to use <FilesMatch ".*\.php$"> around the first allow,deny group and then explicitely allow access to index.php.

Update for Apache 2.4: This answer is correct for Apache 2.2. In Apache 2.4 the access control paradigm has changed, and the correct syntax is to use Require all denied.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow