Wolf87
Wolf87

Reputation: 540

Preventing access to include files

I'm having a problem with .htaccess file rewrite rules. I want to have one .htaccess file in my root directory and to have rule over there to stop people to be able to access files directly over browser. So, for example I have folder blah/includes/file.php and .htaccess file is in blah/ folder, I want to prevent people to be able to just type in browser blah/includes/file.php and get that file, but also I want my functions in app to be able to use those files. I understand that is almost impossible for them to know exact name of my include files but I would like to be sure. Thanks in advance.

here is my code which is not responding:

<IfModule mod_rewrite.c>
    ## Enable Mod Rewrite, this is only required once in each .htaccess file
    RewriteEngine On
    RewriteBase /
    ## Test for access to includes directory
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC]
    ## Test that file requested has php extension
    RewriteCond %{REQUEST_FILENAME} ^.+\.php$
    ## Forbid Access
    RewriteRule .* - [F,NS,L] 
</IfModule>

Note: I'm testing in localhost if that is maybe important.

Upvotes: 0

Views: 118

Answers (2)

Martin Bean
Martin Bean

Reputation: 39389

The quickest way would be just to put a one-line .htaccess file in your includes directory:

deny from all

The other alternative is to place your includes folder outside of your web-accessible directory.

/home/
    /username/
        /includes/
        /public_html/
            /index.php

If you still want to use a RewriteRule, then this is the one you’d use:

RewriteRule ^includes/ - [F,L,NC]

Which would return a 401 Forbidden response trying to access a URI that begin with includes.

Upvotes: 0

Nuramon
Nuramon

Reputation: 1242

Problem is in the first RewriteCond you have a space after /includes/, which throws an error.

BUT: I wouldn't use %{THE_REQUEST}, as it contains the HTTP Request (see http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond). Use %{REQUEST_URI} instead.

So, if you want to forbid access to /<folder>/include/*.php, you can use just this code:

 <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/[^/]+/includes/.*\.php$ [NC]
    RewriteRule .* - [F,NS,L]
 </IfModule>

Assuming your .htaccess lies in the blah/ folder.

Upvotes: 1

Related Questions