3
votes

Note: This question has been asked before several times, but the answers are really bad, totally wrong and/or do not fit the above scenario (because there are several files called index.php). If you like, see [1].

I want to block direct access to all .php files in the application folder (see file structure image) via the .htaccess file in the root folder. There are some solutions for this on the web, but they miss one thing: They don't work if there is more than one file named index.php (which is a realistic scenario like the screenshot shows, see the file in the view/xxx/ folder):

Question: How to block access to all .php files, except the index.php in the root folder ?

enter image description here

2
Sorry if you've tried this, but have you tried moving everything outside of the document root and having index.php reference those files?Dave Chen

2 Answers

5
votes

In .htaccess:

RewriteEngine on
RewriteRule ^/application - [F]

The [F] option instructs it to issue a 403 Forbidden response on all matching URLs.

Or add a separate .htaccess file in /application containing just:

deny from all

Or in your Apache vhost definition:

<Location /application>
  deny from all
</Location>
3
votes

In addition to Niels Keurentjes excellent answer I would like to extend his solution according to my .htacces that uses some very common rewriting patterns (as a lot of people might run into the same problem):

When using URL rewrite rules, then the line RewriteRule ^/application - [F] has to be at exactly that place. It will not work if the line is placed before or below:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

# The new line, blocking direct access to every file in /application and deeper
RewriteRule ^/application - [F]

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]