tags:

views:

226

answers:

4

I want to write URL that work regardless whether the base URL is either of:

http://example.com/myfolder/

http://example.com/

E.g.

<a href="other.html">Other</a>

Should go to

http://example.com/myfolder/other.html

http://example.com/other.html

respectively,

But instead in both cases they go to:

http://example.com/other.html

This is not a problem if the base URLs are

http://example.com/myfolder/index.html

http://example.com/index.html

Any ideas?

A: 

Are you doing this in static HTML? "../other.html" might be a safe bet (assuming you dont get any more nested).

+1  A: 

If you give exactly like

<a href="other.html">Other</a>

it is a relative address and it should work like that.

Remember that when you are linking to a file:

www.example.com/folder/other.html

from:

www.example.com/index.html

you must give the link in index.html as:

<a href="folder/other.html">Other</a>

That is, you have to link to the file using the relative address.

Niyaz
+3  A: 

Relative URIs are always resolved from the base URI which is the URI of the document if not explicitly declared otherwise (see the base element). So what is the base URI in your case?

Gumbo
Yes, there was an errant <base> tag in there that I hadn't noticed, thanks!
EoghanM
+2  A: 

I suspect you were testing this with a base url of:

http://example.com/myfolder

(no trailing slash)

If there is no slash, the browser will think "myfolder" is just a file and not a folder. So click a relative url will not go into that folder.

http://example.com/myfolder/

If the base url is this, then it should work as you expect.

Usually, I prefer absolute URLs just to avoid these headaches. Just about every link in my webapps is in the style:

/myfolder/other.html

Which always points to the same place from any location.

Squeegy
Good call. Though those aren't technically ‘absolute URLs’, which would include the full http:... prefix, but rooted relative URLs. Rooted URLs are almost always the most convenient way to do links as long as you know your app will be mounted at a particular place from the root.
bobince