Skip to content

Instantly share code, notes, and snippets.

@richjenks
Created January 21, 2015 10:25
Show Gist options
  • Save richjenks/57cdb74e87c4637591b1 to your computer and use it in GitHub Desktop.
Save richjenks/57cdb74e87c4637591b1 to your computer and use it in GitHub Desktop.
Redirect to canonical
if (document.querySelector("link[rel='canonical']")) {
// Get current URL
var url = document.URL;
// If query string, get it and append to current URL
if (location.search) {
var query = location.search;
} else {
var query = '';
}
// Get canonical URL
var canonical = document.querySelector("link[rel='canonical']").href;
if (url !== canonical + query) {
window.location.replace(canonical + query);
}
}
@ChriStef
Copy link

ChriStef commented Dec 8, 2018

thank you for this :)

I think this

	if (url !== canonical + query) {
		window.location.replace(canonical + query);
	}``

Should be

	if (url != canonical + query) {
		window.location.replace(canonical + query);
	}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment