marius.7383
marius.7383

Reputation: 169

.htaccess: Redirect / to index.php and block everything else

I'm trying to protect my PHP files against direct access. What I want to allow is direct access to index.php and a directory called public (with CSS, Images, etc.). Access to the root directory / should redirect to index.php:

/ (root): allow -> redirect to index.php
+--index.php: allow
+--public
|  +--... allow
+--[everything else]: block

My current .htaccess file looks like this:

order allow,deny
<Files index.php>
  Allow from all
</Files>
<Files .htaccess>
  Order Allow,Deny
  Deny from all
</Files>

DirectoryIndex index.php

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^/$ /index.php [L]
</IfModule>

It basically works but won't redirect from / to index.php, instead Apache is giving me a 403 error. What am I doing wrong?

Upvotes: 2

Views: 1394

Answers (1)

Sumurai8
Sumurai8

Reputation: 20745

Look at the documentation for Order ..., which you can find here.

Allow,Deny

First, all Allow directives are evaluated; at least one must match, or the request is rejected. Next, all Deny directives are evaluated. If any matches, the request is rejected. Last, any requests which do not match an Allow or a Deny directive are denied by default.

The request for / does not match any rules, so there are no allow or deny directives for it, so it is denied by default. You fix it by explicitly allowing a request to /, and creating a new .htaccess file in the public subdirectory to allow requests there.


In /.htaccess:

order allow,deny
<Files ~ "^(index\.php|)$">
  Allow from all
</Files>
<Files .htaccess>
  Order Allow,Deny
  Deny from all
</Files>

DirectoryIndex index.php

And in /public/.htaccess:

Order allow,deny
Allow from all

Screencast of this working: https://www.screenr.com/BLfN

Upvotes: 2

Related Questions