Liam Kelly
Liam Kelly

Reputation: 3724

How does the browser resolve the relative location of './'?

I am combining many small semi-static, single-page webapps into one larger web site. The backend is a lot of proxies, but the forward facing server basically just make it look like the app was moved from the root filepath to a more specifics one. IE:

/
├── css
│   └── app1.css
├── index.html
└── js
    └── app1.js

would be moved to

/apps/app1/
├── css
│   └── app1.css
├── index.html
└── js
    └── app1.js

This migration has been relatively painless mainly due to the use of ./ in the apps' html files, such that most apps just load their resources relative to their new location. The problem I am having is that some apps are resolving ./ differently. For these trouble cases, the primary html file gets loaded; however, the ./ in the script and style elements are resolving to a higher file-path (IE: I would expect ./ to resolve to /apps/app1 but am getting /apps). It may be a coincidence, but the troubled apps often have additional, non-index HTML files.

What are the rules for how ./ is resolved?

Upvotes: 0

Views: 36

Answers (1)

Quentin
Quentin

Reputation: 944052

  1. Determine the base URL
    • This is usually the URL of the HTML document
    • It might be overridden by the base element
    • For CSS it is the URL of the stylesheet
      • JS is always with respect to the HTML document
  2. Remove everything after the last / in the path section of the URL
    • e.g. the base URL for https://example.com/example/foo?bar=baz#fragment is https://example.com/example/
    • Keep in mind that an HTML document might be visible at the path /example and /example/ and you should avoid this by making one path canonical (I prefer the one that ends in a /) and redirecting to it from the other
  3. Strip the ./ from the front of the relative path
  4. Append the result of step 3 to the result of step 2

A common gotcha is to confuse URLs with file paths. While a simple static site will usually have a direct 1:1 mapping between them, many modern sites will use routing code (e.g. for Express for HTML documents and a separate static route for static files like images, js and css.

Upvotes: 1

Related Questions