Redirect all incoming URL's to the correct canonical URL

  Previous article Next article  

There are multiple URL's to open a page at your website, this might have a bad influence at your SEO status and (Google, Matomo/Piwik) Analytics results. As an example for the homepage:

But in CMS Made Simple also:

This method will redirect the browser to the correct canonical URL with a 301 header: Moved Permanently.

  How to use

1. index.html

To redirect the index.html we can simply use the .htaccess file, like described in this tutorial: Redirect (re)moved pages in CMS Made Simple.

RewriteRule index.html$ [R=301,L]

2. Other URL's

First you have to set the correct canonical URL for each (module) page. This is good practice to have in your website anyway, because it will prevent the duplicate content penalty by Google.
How to create them is described in the tutorial: Base CMS Made Simple page template with automated meta tags.

If your canonical URL's are not good installed within your module templates, it can have a negative effect on your website!
In example module summary pagination pages can be redirected to the wrong page... Be aware of this and test it thoroughly!

The User Defined Tag RedirectCanonical will read the browser URL and the canonical URL. If they don't match the browser will be redirected to the canonical URL.

UDT: RedirectCanonical
 * Source:

$alias = \cms_utils::get_current_alias();
$exclude = isset($params['exclude']) ? $params['exclude'] : '';
$exclude = explode ( ',', ( $exclude . ',error403,error404,error503' ) );
if (in_array($alias, $exclude)) return;

$canonical_url = isset($params['canonical_url']) ? $params['canonical_url'] : '';

if ( $canonical_url != '' )
  if ( strpos( $_SERVER['REQUEST_URI'], '_preview_' ) !== false ) return;

  $browser_url = urldecode ( ( isset($_SERVER['HTTPS']) ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );

  if ( $browser_url != $canonical_url )
    header( 'Location: ' . $canonical_url , true, 301 );

Call this UDT just below the canonical URL Smarty tag in your CMSMS core Page Template:

{$canonical_url = $canonical_url|default:"{$content_obj->GetURL()|lower|default:''}" scope=global}
{RedirectCanonical canonical_url=$canonical_url exclude='page-alias'}

The exclude='foo,bar' parameter is optional and can be used to disable the redirect function at one or more page aliases, i.e. the Search module result page.

Buy Me A Coffee

  Show related articles:

  Comment Form


Click here to open the form



Buy Me A Coffee

CMS Made Simple - Tutorials, Tips and Tricks - CMSMS

Redirect all incoming URL's to the correct canonical URL

  Article optimized for CMSMS 2.x

  Last tested in: CMSMS 2.2.19
  Last updated: 19-10-2019
  Comments: 15

Buy Me A Coffee


Ads help me to help you! Thanks!

Ads help me to help you! Buy products from these advertisers!