Security – allowing index access only with .htaccess

.htaccessSecurity

I have this in my .htaccess file, in the site root:

Options -Indexes
<directory ../.*>
Deny from all
</directory> 

<Files .htaccess>
order allow,deny
deny from all
</Files>

<Files index.php>
Order allow,deny
allow from all
</Files> 

What I'm trying to achieve is to block folder and file access to anything that isn't called index.php, regardless of which directory is accessed. I have the folder part working perfectly and the deny from all rule is working as well – but my attempt to allow access to index.php is failing.

Best Answer

Maybe you are thinking to complicated, just deny all access and then allow access to index.php and the folder itself. For example:

Order allow,deny
Deny from All

<FilesMatch "^(index\.php)?$">
        Allow from All
</FilesMatch>

If you don't even want http://doma.in/folder/ to work you can replace the FilesMatch directive with Files index.php. Keep in mind that it depends on your DirectoryIndex directive what file will be displayed when accessing a folder without filename.

Edit: To answer the question in your comment, I think you will need a more powerfull .htaccess using mod_rewrite. You can't use Directory and DirectoryMatch in a .htaccess file accordingly to the Apache documentation. Because the request is being denied before the RewriteRule can add a trailing slash you can't add the trailing slash with mod_write.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !/index\.php$
    RewriteRule ^.*$ - [F]
</IfModule>

<IfModule !mod_rewrite.c>
    Order allow,deny
    Deny from All
</IfModule>