Let me auto_prepend_file my js files with:

var SITE_ROOT = 'http://www.mydomain.com';

Is this completed in .htaccess enjoy it can for php files, if that's the case, how?!!!

You can accomplish what you are seeking having a mod_rewrite rule along with a small php file:


// Open a javascript file provided by ?file=somefile.js and to prepend some content

$file = $_GET['file'];

// Checks that the file exists on the system and that it ends in '.js'
// The RewriteCond's do the same thing, but this prevents direct 
// calls to js_wrapper.php as well
if(!is_file("./" . $file) OR !preg_match('#\.js$#', $file)) {
    // 404
    header("HTTP/1.0 404 Not Found");
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
<title>404 Not Found</title> 
<h1>Not Found</h1> 
<p>The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found on this server.</p> 


header("Content-type: text/javascript");

// Begin prepended content
// Auto-prepended by js_wrapper
var SITE_ROOT = 'http://www.mydomain.com';
// End auto-prepend

// Output the original file
echo file_get_contents($file);


# Pass all requests to js/some/script.js through js_wrapper.php?file=js/some/script.js
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} \.js$
RewriteRule ^js/(.*)$  js_wrapper.php?file=js/$1  [L,NC,QSA]

You need to customize the RewriteRule directive to mirror another path in case your scripts aren't within folder named 'js'.


Since inside your example you are basically determining a flexible in the beginning, if this sounds like all you are searching to complete, you need to have the ability to make this happen using a <script> block inside your <head> block from the page such as the js scripts. The js scripts will have the ability to access any variables you define there. This really is easier, simpler to keep, uses less 'magic' (people reading through the made html source and js will not understand in which the prepended information is originating from unless of course they read .htaccess), and it is the way i would most likely do what you are attempting to accomplish.

... stuff ...
    <script type="text/javascript">
        var SITE_ROOT = 'http://www.example.com';
    <script type="text/javascript" src="/js/some_script.js"></script> 
    <script type="text/javascript" src="/js/some_other_script.js"></script> 
... stuff ...

I believe you are looking for mod_layout.