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

Johan picture Johan · Aug 27, 2009 · Viewed 234k times · Source

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.

UPDATE:

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.

UPDATE 2:

The index.php is in a folder www.myadress.com/myfolder/index.php

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

Answer

Residuum picture Residuum · Aug 27, 2009

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 127.0.0.1

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

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
</FilesMatch>

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.