简体   繁体   中英

.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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM