Categories
Programming

How to setup canonical URL in Yii2

You can place a canonical URL to a page using your view file.

To generate the canonical URL, we can use the canonical ( ) in the URL helper class. Also note this method consider if the current website URL is applicable to any URL rules specified and if so generate the canonical URL based on that.

yiihelpersUrl::canonical()

One catch I found with this canonical URL method is that all the parameters in the URL are captured and parsed into the generated URL. So If you need to ignore a set of parameters. you would need to create your own canonical URL method where you can pass the parameters that need to be ignored.

The in the view file call the canonical method as following.

$this->registerLinkTag(['rel' => 'canonical', 'href' => Helper::canonical()]);

You are done. Now your canonical URL should be visible in the page header.

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments