I recently got into web development and created a simple site. I wanted to link a JavaScript file (file.js) to my site from one directory up but no matter what I’ve tried it doesn’t work.
When looking for solutions people said to use relative paths (which is what I tried using from the start), using "../file.js" to try and move one directory up and then look for the file.
The server is running on apache for Debian 11 and my folder structure is as such:
var
|
www - file.js
|
html - index.html
and my code for loading file.js is as such:
<script src="../file.js"></script>
Any help with this issue would be great.
3
Answers
I think the issue is that you cannot define the relative path above the document root of the site, which would be the html folder. Depending on the webserver, this may be forbiden.
Ideally you would create a scripts folder inside the html folder and point to it that way.
/var/www/html/index.html
/var/html/scripts/file.js
A client-side browser is unaware of the folder structure present above the root of the website at the backend. There are ways to enable it with permissions but its not recommend as it can create security leaks by accident.
I suppose "html" is the public folder for your apache server. You need to make "www" as the public folder.
Instead of ../file.js its recommended to put the absolute path, address of your server continued with the path of the file inside the public folder.
If you are running apache on localhost port 80 and "www" as public folder/root, it would be "http://localhost/file.js", here we do not need to put the port number as http by default runs on port 80.
PHP resolves paths on the computer’s file system, whereas web browsers resolve paths on the URL.
The browser can only read data that the web server will send to it, and by keeping the scripts directory outside of the document root it’s not available via the web server.
Therefore any .js files must be in the /html directory.