SEO Canonical URL Recipe for GTM

March 20, 2017 | Bounteous x Accolite

Adds a rel=”canonical” <link> element to pages. The default uses a canonical URL with https as the protocol, removes www from the hostname, and removes the query string, but additional variables are provided for other options (see instructions below).

FAQ: Does it really work to add data for search engines dynamically with JavaScript in GTM?

Google will use this data in its crawls. This was first confirmed by Simo Ahava in the experiments detailed here. Other search engine behavior may vary. This method using GTM is a workaround for enhancing Google search results when other options to edit your site’s source code are not available to you.

Ingredients

Tags

CU - SEO - Canonical URL - LunaMetrics Plugin

Variables

Page Hostname - No WWW

Page Hostname - With WWW

Page Protocol

Page Query String

Page URL Canonical - HTTPS, No WWW

Page URL Canonical - HTTPS, WWW

Page URL Canonical - Protocol Relative, No WWW

Page URL Canonical - Protocol Relative, WWW

Instructions

1. Download Container File

Download the container JSON file.

(You may need to right-click on the link and choose “Save Link As” or “Save Target As” to save the JSON file to your computer.)

2. Import JSON File into GTM

Log into your own Google Tag Manager container and head to the Admin section of the site. Under Container options, select Import Container. Check out this blog post for more details about importing a container file.

3. Preview & Publish

Use the Preview options to test this container on your own site. If everything looks good, go ahead and publish!

Optional - Update the Canonical URL Format

This recipe uses a Custom HTML Tag to include a canonical URL. The default setting takes the current page’s URL, uses https as the protocol, removes www from the hostname, and removes the query string.

Other URL variables (using a relative protocol to detect http or https, using or omitting www from the hostname) are also available. You can replace the reference in the CU – SEO – Canonical URL – LunaMetrics Plugin tag to the {{Page URL Canonical – HTTPS, No WWW}} variable with one of the other options if you prefer.

If you wish to include all or part of the query string, you can use GTM’s URL variables to include the full query string (included in this container as the {{Page Query String}} variable), or to selectively pull out values from the query string.