I am creating a website on localhost
. I want to make all of link resources in my website to relative path ( I mean only internal resources).
website is located in
http://localhost/mywebsite
I read this useful question Absolute vs relative URLs.
I found differences between /images/example.png
and images/example.png
<a href="/images/example.png"> Link To Image</a>
Above relative path should return ROOT_DOCUMENT/images/example.png
because of /
at first of url. As ROOT_DOCUMENT
is something like /wamp/www/mywebsite
But when I tested it, it only return /wamp/www/images/example.png
And I should add manually my website folder /mywebsite/images/example.png
to relative path.
<a href="mywebsite/images/example.png"> Link To Image</a>
And it is not useful because of changing the name of mywebsite. So:
You say your website is in http://localhost/mywebsite
, and let's say that your image is inside a subfolder named pictures/
:
Absolute path
If you use an absolute path, /
would point to the root of the site, not the root of the document: localhost
in your case. That's why you need to specify your document's folder in order to access the pictures folder:
"/mywebsite/pictures/picture.png"
And it would be the same as:
"http://localhost/mywebsite/pictures/picture.png"
Relative path
A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:
"pictures/picture.png"
But there are other perks with relative paths:
dot-slash (./
)
Dot (.
) points to the same directory and the slash (/
) gives access to it:
So this:
"pictures/picture.png"
Would be the same as this:
"./pictures/picture.png"
Double-dot-slash (../
)
In this case, a double dot (..
) points to the upper directory and likewise, the slash (/
) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:
"../picture.png"
You can play around with them as much as you want, a little example would be this:
Let's say you're on directory A
, and you want to access directory X
.
- root
|- a
|- A
|- b
|- x
|- X
Your URL would look either:
Absolute path
"/x/X/picture.png"
Or:
Relative path
"./../x/X/picture.png"