Search code examples
http-redirectgetjekyllgithub-pages

Redirecting based on GET request data in GitHub pages


I used to have a dynamic website, which made use of GET requests to specify pages, e.g. https://www.example.com?n=about. I have now moved over to a Jekyll site on GitHub Pages (with a custom domain), but ideally would like these old links to work.

Currently, as one would expect, such links simply return the index page. Is there any way to get the above url to redirect to https://www.example.com/about/?


Solution

  • There is no built-in option in GitHub pages. You cannot redirect URLs using a .htaccess file on the server.

    But you can of course use client-side Javascript code:

    <script>
      var queryString = window.location.search;
      if (queryString === "?n=about") {
        window.location.replace("https://www.example.com/about/");
      }
    </script>
    

    For different URLs, you'd need to store the mapping between the old and new URL, and then use a switch statement (or an if/else) to perform the redirect.

    <script>
      var queryString = window.location.search;
      var mapping = {
        "?n=about": "https://www.example.com/about/",
        "?n=home": "https://www.example.com/home/",
        "?n=test": "https://www.example.com/test/"
      };
      
      switch (queryString) {
        case "?n=about":
          window.location.replace(mapping["?n=about"]);
          break;
        case "?n=home":
          window.location.replace(mapping["?n=home"]);
          break;
        case "?n=test":
          window.location.replace(mapping["?n=test"]);
          break;
      }
    </script>
    

    Learn more about the location.search property.