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

Viewed 251572

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.

13 Answers

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

Here example from my CMS EFFCORE.

Apache 2.4 notation:

<If "%{REQUEST_URI} -strmatch '*.php'">
    Require all denied
</If>

<If "%{REQUEST_URI} -strmatch '/index.php'">
    Require all granted
</If>

##########################
### SINGLE ENTRY POINT ###
##########################

RewriteEngine On
RewriteRule ^.*$ index.php [L]

NGINX notation:

server {
    listen 127.0.0.1:80;
    server_name 127.0.0.1;
    root /var/www;
    location ~* .*\.php$ {
        deny all;
        error_log off;
    }
  # SINGLE ENTRY POINT
    location / {
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
        include /usr/local/etc/nginx/fastcgi.conf;
        fastcgi_param SCRIPT_NAME /index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    }
}

IIS 7.5+ notation:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="*.php files protection" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*.php" />
                    <action type="CustomResponse" statusCode="403" subStatusCode="0" statusReason="Forbidden" statusDescription="Forbidden" />
                </rule>
                <rule name="SINGLE ENTRY POINT" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="^.*$" ignoreCase="true" />
                    <action type="Rewrite" url="index.php/{R:0}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
        <defaultDocument>
            <files>
                <clear />
                <add value="index.php" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>
Related