Search code examples
javascriptreferencepathsrcdocument-root

Possible to reference javascript files above document root?


I am working on a project where http://www.mywebsite.com/index.html is in /var/www/public, which is the document root (according to /etc/apache2/sites-available/000-default.conf). I have javascript files in /var/www/js that I would like to reference in my /var/www/public/index.html file. Here is what I've tried so far

<script src="/js/js_file.js"></script>
-
<script src="js/js_file.js"></script>
-
<script src="../js/js_file.js"></script>
-
<script src="../../js/js_file.js"></script>

None of these work.

How do I reference javascript files outside of the document root directory?


Solution

  • You could achieve this by adding a rewrite rule to Apache config. See the apache url rewrite guide. The idea is to map an internal directory to a url string that the user has entered.

    Something like this:

    RewriteCond   %{HTTP_HOST}  \.mywebsite\.com$
    RewriteRule  ^/js/(.*)\.js$ var/www/js/$1
    

    Would allow public users to reach var/www/js/test.js via the public url mywebsite.com/js/test.js.