Jul 15, 2019

f Comment

HTML CSS Link to One Level of the Directory Tree up from the Document Root

Amazon Let's talk about a situation where you are running a web server and you'd like your website to be able to access a resource outside of the document root such as one level up from the document root.

Suppose your website mysite1's document root is set as:

/usr/share/nginx/root/mysite1

Your website can access any resource inside /usr/share/nginx/root/mysite1 folder such as the following:

/usr/share/nginx/root/mysite1/index.html
/usr/share/nginx/root/mysite1/my.css
/usr/share/nginx/root/mysite1/js/my.js

My server has another file /usr/share/nginx/root/master-css/my.css, and I'd like my website mysite1 to access /usr/share/nginx/root/master-css/my.css. How do I do that?

I wanted to do this because I am running multiple websites and I'd like them to share one single CSS folder since they pretty much have the same styles.

I am running Ubuntu 14.04, nginx 1.4.6. My solution works with all kinds of web resources, including CSS, JavaScript, images.

Concept

First of all, suppose your website http://www.mysite1.com/a/page.html has the following markup inside it:

<link rel="stylesheet" href="../master-css/my.css" type="text/css" />

This CSS file will resolve to http://www.mysite1.com/master-css/my.css.

However, suppose your website http://www.mysite1.com/page2.html has the same markup inside it. Guess what? This CSS file will still resolve to http://www.mysite1.com/master-css/my.css. This is because when you are already at the document root, and you can't go up one level of the directory tree via double period (..) anymore.

Since there's no master-css folder at /usr/share/nginx/root/mysite1, this web resource access will return a 404 file not found.

Solution

Here's how you can have your web server access a resource (CSS, JavaScript, image, etc.) outside of the document root. Simply make a simbolic link from master-css to ../master-css at /usr/share/nginx/root/mysite1 on your server box like this:

cd /usr/share/nginx/root/mysite1
ln -s ../master-css/ master-css

When you are done and list the files in the directory via the "ls -al" command, you should see something like this:

lrwxrwxrwx 1 root root 8 Jul 15 11:16 master-css -> ../master-css/

Now assuming your website http://www.mysite1.com/page2.html has the following markup inside it:

<link rel="stylesheet" href="master-css/my.css" type="text/css" />

When your web server tries to resolve this CSS file, it'll follow the symbolic link and go to the correct folder /usr/share/nginx/root/master-css to retrieve the file my.css.

Questions? Let me know!


Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael