Changing Canonical URL with NGINX
A Canonical URL is an HTML element that we use to prevent SEO from detecting is as a duplication, by simply telling them that this page is the same as the canonical URL. This way, when the search engine found the two similar page, we tell it that it should show the canonical instead.
Say you have a company with a domain that ranks high in the SEO, placed in the first page or even the first place in the Google search. But somehow you decided to change the name of the company and you want to change the domain name. We know that ranking a new domain is not an easy thing to do and it takes time.
There are 2 ways to promote the new domain, the first one is by redirecting all request from the old domain to the new domain. 301 redirect signals a permanent redirect, meaning that everything now must redirect to the target domain and the old domain or page is no longer relevant, useful, and has been removed. This way, all the traffic will be redirected immediately to the new target and the search engine will also update it to the new one.
But we can also achieve similar results by only changing the canonical URL. So if you decide that you still want to keep the old domain or page but want to tell the search engine to move to the new domain instead, you should change the canonical URL to the new one. If you have a good ranking in the previous domain, you will see in no time that it will be replaced by the search engine to the new domain, similar result when you redirect it with 301.
If you are hosting your domain in Wordpress, this can be done by various plugins that provides customization for SEO. However, almost all of the plugins will require you to subscribe to the premium license if you want to change the canonical URL. But if you are hosting your own wordpress and you have control over the web server, don’t worry! We can change it from the web server configuration since all request will need to communicate to the web server and we can modify the request and response there, meaning that changing canonical URL from the web server is totally possible!
If you are using NGINX as the web server, you can simply use the HTTP Sub Module. This module will allow you to modify a response by replacing one specified string by another. As Canonical URL is an HTML element sent in the response, we can change it by adding the following:
http {
...
sub_filter '<link rel="canonical" href="https://old-domain.com/"' '<link rel="canonical" href="https://new-domain.com/"';
...
}
The configuration above will make sure that only the HTTP canonical element will be changed from https://old-domain.com/ to https://new-domain.com/. And there you go! You don’t need all the subscription just to change the canonical URL.