A custom canonical URL for one article

I've recently contributed an article to a different blog. To avoid issues around duplicated content I wanted to get a custom canonical URL into place for the original version, which should point to the new location.

This was quite easy to implement based on Pelican with the following approach:

  • Add a new meta tag into the post, I called it canonical_url.
  • Adjust the template article.html, so that it uses this value if it is present.

Add the data into the article

Adding the meta information is straight forward. The following example shows a restructured text snippet:

Example article

:canonical_url: https://www.example.com/article-home-base

Adjust the template

The templates are based on Jinja2. In my base template a block called canonical_rel was already present, so I just had to adjust it.

The old version looked like this:

{% block canonical_rel %}
  <link rel="canonical" href="{{ SITEURL }}/{{ article.url }}">
{% endblock %}

Adding an if-condition which checks for the presence of the new meta attribute gets the job done:

{% block canonical_rel %}
  {% if article.canonical_url %}
    <link rel="canonical" href="{{ article.canonical_url }}">
  {% else %}
    <link rel="canonical" href="{{ SITEURL }}/{{ article.url }}">
  {% endif %}
{% endblock %}


That's all it takes for this tweak. This principle can be adapted also to other needs based on custom meta information from the articles.


comments powered by Disqus