Redirect all incoming URL's to the correct canonical URL
Previous article Next articleThere 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.
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: https://cmscanbesimple.org/blog/redirect-all-incoming-urls-to-the-correct-canonical-url
*/
$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 );
exit;
}
}
Call this UDT just below the canonical URL Smarty tag in your CMSMS core Page Template:
{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.
Comment Form
3 Comments
Improved UDT code for multiple page aliases in the exclude parameter.
Thanks Denis.
I added the core error pages to the exclude parameter.
It works now by default!
Error page 404, which was created from "Content manager" doesn't working with this UDT...