Search code examples
htmlurlrelative-pathabsolute-path

Absolute or Relative URL if my website may not be at the root folder?


I am developing a website on a web server which can be accessed by 2 URL: mywebsite.example.com or example.com/mywebsite. For example, when I access mywebsite.example.com/images/abc.jpg and example.com/mywebsite/images/abc.jpg, I get the same picture.

The problem is, I have many links inside my website, and I am not sure should I use an absolute or relative path.

From another question Absolute vs relative URLs I found someone suggesting using URL relative to root (like /images/abc.jpg), however when I access the website using example.com/mywebsite, every link just break.

For relative paths, I found it hard to manage since webpages are in different folders, but using the same template which contains some links. It means I have to manually set some links as ../ and some as ./.

I have also tried using <base> tag however it messes up with anchor. Even if I try to include the full path before the # symbol, some jQuery libraries does not function properly since they get the value inside the attribute href directly, but not extracting the part after #.

Would there be any better practice or suggestion?


Solution

  • I think you should use relative urls, and concentrate your searchs on how to use relative urls in templates, that would be resolved relatively to the final page.

    I don't know the technology you are using for templating, but I see two common solutions :

    • declare a "relative path" variable in the template, and then override it in the different pages, with the new relative path. Use this relative path as a prefix for all urls
    • delegate urls construction to a service that would know the final page. Somethinkg like resolveUrl(..)