Eyad Fallatah
Eyad Fallatah

Reputation: 1948

.htaccess to restrict access to folder

I have a php file that inherits (includes) another PHP files. All inherited files are located in one folder called "includes". I want to be able to restrict any direct access to this folder. Only PHP files within the server can communicate with the files in the "includes" folder. How can I use .htaccess to accomplish such goal?

FYI, I used the following code and it did not work

Order deny,allow
deny from all

Any help would be appreciated

Upvotes: 10

Views: 28487

Answers (5)

Amit Verma
Amit Verma

Reputation: 41219

You can deny direct access to the folder using the following Directives in htaccess or server.config contex :

Mod-alias based solution

Redirect 403 ^/folder/.+$

This will redirect all files and dirs of /folder/ to 403 forbidden error page.

Mod-rewrite base solution :

RewriteEngine on

RewriteRule ^/?folder/.+$ - [F]

Upvotes: 1

Keith
Keith

Reputation: 966

Depending on possible other options set at a higher level you may need to use:

Satisfy all
Order deny,allow
Deny from all

I ran into this when the upper directory defined basic authentication including the line:

Satisfy any

This was preventing my deny from all to take effect because the users were authenticated.

Upvotes: 0

Reuben
Reuben

Reputation: 4266

If you don't have the option of actually moving the "includes" folder outside of the Document Root area, and using the include_path (i.e. you can't get to it from web), then enter

deny from all

in a .htaccess directory in that directory.

However, alternative is to use a DEFINES directive to only allow access to those include programs by specific authorised files. For example, put

<?php defined('ACCESS_ALLOWED') or die('Restricted Access'); ?>

in the top of the include files, and then put

<?php define('ACCESS_ALLOWED', 1); ?>

in the programs that are allowed to include those files.

This will prevent casual GETs to those include files from running them, and will work for any web server, not just those supporting htaccess files.

Upvotes: 19

Ruel
Ruel

Reputation: 15780

You can actually just use an index.php and pass a 404 header using header():

header('HTTP/1.1 404 Not Found', 404);

IMO, this is better than a 403, since it's like the folder doesn't exist. As for the include files, put this line above the first include/require line of the main file:

define('INCLUDED', true);

And on every file in the include directory, put this at top most part.

if (!defined(INCLUDED)) {
    header('HTTP/1.1 404 Not Found', 404);
}

Upvotes: 2

jujule
jujule

Reputation: 11531

in your includes/.htaccess :

Order deny,allow
deny from all

Upvotes: 3

Related Questions