Apache prevent execution of PHP files in a particular directory

apache-2.2

Hi not sure if this is the correct forum but I am wondering about preventing execution of certain file types in a particular directory. A quick google search indicates that an htaccess file containing…

Options -ExecCGI
php_flag engine off
SetHandler none
SetHandler default-handler
RemoveHandler .cgi .php .php3 .php4 .php5 .phtml .pl .py .pyc .pyo

should do the trick. What I am wondering does this still allow php files in other directories to perform actions on files in that directory. For example the directory has images in it and there is an a php file contained in another directory that creates thumbnails of those images and stores them within the original directory.

Best Answer

I use in Centos 6.10 for multiple folders in virtual host .conf definitioin file:

<DirectoryMatch ^/var/www/mysite/htdocs/(nophpexecutefolder1|nophpexecutefolder2)>
       php_admin_value engine Off
</DirectoryMatch>

However, even though it doesn't parse php code the usual way it still outputs from a .php things such as variable declarations and text when doing echo e.g.

<?php

echo "<strong>PHP CODE EXECUTED!!";

$a=1;
$b=2;

echo $a+$b;

The above produces in web browser?

PHP CODE EXECUTED!!"; $a=1; $b=2; echo $a+$b;

This could potentially expose some code to users which isn't ideal. The same happens when use OP's code.

Therefore, it's probably best to use the above in combination with the following in .htaccess:

<FilesMatch ".*.(php|php3|php4|php5|php6|php7|php8|phps|pl|py|pyc|pyo|jsp|asp|htm|html|shtml|phtml|sh|cgi)$">
 Order Deny,Allow
 Deny from all
  #IPs to allow access to the above extensions in current folder
  # Allow from XXX.XXX.XXX.XXX/32 XXX.XXX.XXX.XXX/32
</FilesMatch>

The above will prevent access to any of the above file extensions but will allow other extensions such as images, css etc. to be accessed the usual way. The error when accessing .php:

Forbidden

You don't have permission to access /nophpexecutefolder1/somefile.php on this server.