Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to prevent certain directories of a web site from being directly accessed?

Which is the best way to prevent certain directories of a web site from being directly accessed?

1- Creating and placing a .htaccess file in each directory we want to protect and place the next line in it:

Deny from all

2- Creating and placing a index.php file in each directory we want to protect and place only the next line of code in it (which will redirect to homepage of the website):

<?php header("Location: http://" . $_SERVER['HTTP_HOST']); ?>

3- Something else (what is it?)

like image 268
Amr Avatar asked Sep 16 '12 20:09

Amr


1 Answers

As mentioned in the comments, the safest way is to place content or directories outside the web server's public document root. This will ensure that content will not be served even if an .htaccess file is deleted or if the server does not allow .htaccess overrides.

To determine your document root you can just echo the PHP $_SERVER['DOCUMENT_ROOT'] variable. So if your root is /var/www/html, you can create a folder /var/www/protected_folder and Apache (or other web server) will never serve it (unless the http.conf file is altered to modify the document root folder).

If the folder must be in the document root, then using an .htaccess file to either DENY or redirect is a good alternative.

As TerryE mentioned, you could also use OS-level file permissions to deny the Apache user access to the folder (set a different user as the owner and then set permission on the folder to 700, for example). If they try to access the folder they'll get a 403 Forbidden Error which you may not want to show (though you could set up a custom 403 error handler in http.conf or htaccess). Depending on specifically what you are trying to do you may want this approach, as it will also let you prevent access from scripts (i.e. PHP include() etc) if you want to, as PHP runs under the webserver user by default. The major downside of this approach is that file permissions are often not preserved during migrations (if they're not done correctly) and file permissions can sometimes be reset inadvertently when altering parent folder permissions with a recursive flag (whereas it's unlikely that someone would inadvertently move a folder into the document root).

like image 70
Ben D Avatar answered Sep 19 '22 13:09

Ben D