You could use your .htaccess
to reroute requests to a PHP file like: (I'm not testing it, but it should work, I think)
Options -MultiViews
RewriteEngine on
RewriteBase /
#if not a directory and ends in .js, then rewrite URL to /dir/js_handler.php and append the query string
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} \.js$
RewriteRule ^(.+)$ /dir/js_handler.php [L,QSA]
Your .htaccess
file generally will go at the root of your site, or you could put it in the folder containing all your javascript files.
Then in your js_handler.php
file, you could do some sort of check.
Easiest (but not secure) option would be:
if ($header['Referer']=='mydomain.com'){
//it was requested by loading the HTML page
} else {
//it was requested directly
}
To get $header
see this post.
A much more thorough route would be to use a randomly generated access key and verify against that. You could have a cron job generate a new key every five minutes or so and use SQL or write it to a file. For example:
$file_path = //some path
$randKey = generateRandomKey();
$keyArray = json_decode(file_get_contents($file_path),true);
$keyArray[1] = $keyArray[0];//move the first element to the 2nd.
$keyArray[0] = $randKey; //set the first element to $randKey
file_put_contents($file_path,json_encode($keyArray) );
Then when you deliver an HTML page (assuming you're doing it via PHP):
<?php
$keyArray = json_decode(file_get_contents($file_path),true);
$randKey = $keyArray[0];
?>
<head>
<script type="text/javascript"
src="/path/to/myscript.js?secret=<?=$randKey?> ></script>
</head>
Then in js_handler.php
:
$keyArray = json_decode(file_get_contents($file_path),true);
if (in_array($_GET['secret'],$keyArray){
//deliver the js file
} else {
//deliver 404 page
}
For the location of the script use $_SERVER['REQUEST_URI']
. You should be able to just include
the javascript file and let the script terminate. You may need to set the headers, though. I'm not totally sure and can't test it right now.