Search code examples
phpapache.htaccesssecurity

Apache only allow index.php - not working from root directory


I have Apache 2.4 web server for PHP and I want to make it secure using .htaccess, so that noone will be able to access my files other than index.php in root folder (var/www/html/index.php). The problem is that with my configuration it allows index.php only from localhost/index.php and not localhost/. I tried redirecting but it doesn't change much:

DirectoryIndex index.php

# Redirect the root (/) to index.php
RewriteEngine On
RewriteRule ^$ /index.php [L]

# Deny all requests by default
Require all denied

# Allow only access to index.php
<Files "index.php">
  Require all granted
</Files>

Solution

  • changing

    <Files "index.php">
      Require all granted
    </Files>
    

    to

    <Files ~ "^(index\.php|)$">
      Require all granted
    </Files>
    

    fixes the issue;

    <Files ~ "^(index\.php|)$">:

    • ~ indicates regex
    • then we are searching for index.php or empty string (which is root directory in this case)