Search code examples
urlsingle-page-applicationdeep-linkinghtml5-history

Using the History API to 'rewrite' the displayed address, when the user visits the URL the server gives a 404 error


The History API is being used to rewrite/set the displayed address as part of SPA navigation, for example:

history.pushState({}, `example`, `/example.htm`);

The example.htm page does not exist on the server, but, my client-side code is written in a way that when the page loads and this page is in the address the view is updated with "example.htm" content (ie. "deep-linking").

The problem is that when the user bookmarks the address and tries to visit it again later the server gives a 404 error. The server has "default documents" configured, and if no document is specified the server delivers the expected html and javascript without error.

In what ways can the URL be formatted so the default document loads, but still passably looks like a typical web address to the average end-user? As a design-constraint query-string parameters cannot be used (ie. no use of ? or &), and the server code cannot be changed to prevent the 404.


Solution

  • Based on CBroe's comment, after reading through URI Fragment docs, I believe I can construct a URL with the following format:

    https://myserver.com/#/example.htm

    Then in my client-side code, I can check for /#/ and (if found) parse out the remainder of the URL to serve as a route key.

      let startIndex = document.location.href.indexOf("/#/");
      if (startIndex > -1) {
        // extract page name
      }