I am trying to stop direct access to a subdirectories and the php files within subdirectories. I\'ve added the following code below to the .htaccess file within the subdirec
You can use mod_rewrite to restrict access to all bet certain files in a directory. Add this to the .htaccess
in that directory.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !(jsonp)|(ws)|(ajax)
RewriteRule .* - [R=404,L]
Just replace the jsonp ws ajax with the name of your files.
If your ajax function access some file that is inside that folder, you can't. As the AJAX is a requisition sent from the client browser.
I would put apache directives aside, and -perhaps- focus on a php-based solution:
Make sure your file containing the jquery ajax call has a ".php" extension.
(of course inside that file, all jquery must be contained within <script>
and </script>
tags.
Inside your jquery function just before the ajax call, type that:
<?php $_SESSION["allow"] = "granted" ?>
(php tags run even if they are contained in "script" tags)
Open your ajax (php) file and at the very top type this:
<?php session_start(); if((!isset($_SESSION['allow'])) && ($_SESSION['allow']!="granted")){die();}else unset($_SESSION['allow']); (...rest of your php code here...) ?>
... and you are Done!
P.S. Naturally, you may (or better: should) rename the sessions and give them different or more complex values, but I was just trying to point out the basic idea... Happy coding!
I found simplest solution using session.
suppose you want to restrict direct access of your db_config.php,
you can do like this. open your index.php from root and add this in first line of your code:
$sess = session_start();
$_SESSION["nuclear_weapon_key"] = "lolva";
now go to sub_dir -> open db_config.php add this one the top of the page:
$sess = session_start();
if(isset($_SESSION['nuclear_weapon_key']) && $_SESSION['nuclear_weapon_key'] === "lolva"){ } else{ echo "LOL"; die();}
repeat this for whatever ajax/jquery containing file/s.
it worked for me.
Put this code in your DOCUMENT_ROOT/.htaccess
file:
RewriteEngine On
## disable direct access (but allow internal or AJAX requests)
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/ [NC]
RewriteRule ^subdir(/|$) - [F,NC]
Replace www.domain.com
by your own domain name.
Note that this uses %{HTTP_REFERER}
header to do this blocking and it is possible to manipulate this header value.