How To Create A Custom Route

When accessing the URL https://www.site.com/mypage LiteCart looks for a document in the folder pages/ named mypage.inc.php. Sometimes when that is not enough, you can add custom routes by creating a new routing module placed in includes/routes/.

You can rewrite the URL and/or you can set up URL aliases.

URL Rewrite Example

In this example, we are creating a custom URL for mypage depending on the selected language.

includes/routes/url_mypage.inc.php:


<?php
  class url_mypage {  // The class name url_{pagename} must match the page filename -> pages/{pagename}.inc.php

  // For incoming traffic.
    function routes() {
      return [
        [
          'pattern' => '#^my-fantastic-url-(\d+)$#',  // This is the regex pattern for resolving a rewritten url back to a resource.
          'page' => 'mypage',  // This is the target document meaning pages/mypage.inc.php
          'params' => '',  // Establish URL query parameters based on the result of the regex. E.g. page_id=$1 etc.
          'redirect' => true,  // If accessing a non rewritten url, let's do a 301 redirect.
        ],
      ];
    }

  // For outgoing traffic.
    function rewrite($parsed_link, $language_code) {

      switch($language_code) {
        case 'de':
          $parsed_link['path'] = 'mein-fantastisches-url';
          break;
        default:
          $parsed_link['path'] = 'my-fantastic-url';
          break;
      }

      return $parsed_link;
    }
  }

Alias Routes Example

includes/routes/url_old_oscommerce_links.inc.php:


<?php
  class url_old_oscommerce_links {

    function routes() {
      return [
        [
          'pattern' => '#^.*-c-([0-9]+).html$#',
          'page' => 'category',
          'params' => 'category_id=$1',
          'redirect' => false,
        ],
        [
          'pattern' => '#^.*-p-([0-9]+).html$#',
          'page' => 'product',
          'params' => 'product_id=$1',
          'redirect' => false,
        ],
      ];
    }
  }

Please note incoming URL query parameters are not parsed when processing a page request.

Revisions

Recently Edited Articles
This website uses no cookies and no third party tracking technology. We think we can do better than others and really think about your privacy.