Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mike-north/34a1daac9d14ce847fa1 to your computer and use it in GitHub Desktop.
Save mike-north/34a1daac9d14ce847fa1 to your computer and use it in GitHub Desktop.
Github Org and User Pages - Hash navigation workaround

Github Org and User Pages URL Redirect

If you are using "hash" navigation for a single page app on Github Org or User Pages, you may run into a URL problem.

The Problem

Users who visit a url like

http://myorg.github.io/upcoming-events

will be sent to the github page for a repo like

git@github.com:myorg/upcoming-events.git

Ultimately you may want them to be sent to a page like

http://myorg.github.io/#/upcoming-events

The Workaround

You can create this upcoming-events repository, and put this index.html file in its gh-pages branch. It will take the "path" component of the url, move it to the "hash" component of the url, and redirect the user to that page

How it works

// Create an anchor tag. It will be quite useful!
var anchor = document.createElement('a');

// Set the "href" attribute to the user's current URL
anchor.href = window.location.href;

// Move the "pathname" property to the "hash" property
//   This will convert something like
//       http://myserver.com/mypage
//   to  http://myserver.com/#/mypage
anchor.hash = anchor.pathname;
anchor.pathname = '';

// Redirect the user
window.location.href = anchor.href;
<!DOCTYPE html>
<html>
<head></head>
<body>
<noscript>
<div style="text-align: center;">
<h3>
You must have JavaScript enabled to use this page
</h3>
</div>
</noscript>
<script type="text/javascript">
var anchor = document.createElement('a');
anchor.href = window.location.href;
anchor.hash = anchor.pathname;
anchor.pathname = '';
window.location.href = anchor.href;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment