Search code examples
apache.htaccesshttp-status-code-403

Sending access is denied error using htaccess on apache for all files but a certain one


I have a folder containing various .php files, and I want to prevent direct access to them, BUT to index.php.

This is what I got so far, and it appears working:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ /403.php/$1 [R=403]
</IfModule>

Is this the correct way to do it? Also note that 403.php doesn't actually exist among the files I have in the folder.

EDIT: to better clarify what I'm trying to do -- I have a folder (we can assume named "includes") containing an index.php file, and various other files which are included by index.php.

I don't want users / malicious bots / whoever to be able to directly access anything in "includes" other than index.php.

In case they reach anything else (regardless whether the file exists or not), I want to send to the browser a 403 - Access Denied HTTP response code.


Solution

  • The correct way is to use the F flag, which simply returns a 403 forbidden and you can use - as the target which just means "do nothing and let the URI pass through unchanged":

    RewriteEngine on
    RewriteCond $1 !^(index\.php)
    RewriteRule ^(.*)$ - [L,F]
    

    Or you can try combining the condition with the rule:

    RewriteEngine on
    RewriteRule !index\.php$ - [L,F]