---
type: Article
title: 11ty conditional canonical
description: How I created a conditional canonical tag in my 11ty nunjucks base template.
resource: https://www.simoncox.com/short-articles/2023-02-13-11ty-conditional-canonical/
tags: [Shorticles, Eleventy]
timestamp: 2023-02-13
---

GSC was flagging some Canonical issue on this site so I decided to add the canonical using the page.url parameter in my base.njk nunjucks include. 

`{% raw %}<link rel="canonical" href="https://www.simoncox.com{{ page.url }}">{% endraw %}`

However, I have already included a Canonical in the frontmatter of some of my posts and there may be reasons why i'd want the canonical to be on a different url. So I added a conditional to state that if the frontmatter for canonical exists then use it else fall back to the standard page url version. And that gave me this:  
`{% raw %}{% if canonical %}<link rel="canonical" href="{{ canonical }}">{% else %}<link rel="canonical" href="https://www.simoncox.com{{ page.url }}">{% endif %}{% endraw %}`

Simple but effective.
^ to [MrQuest for the tip showing me how to display raw njk code!](https://mrqwest.co.uk/blog/escaping-code-in-11ty/)

[Read full article](https://www.simoncox.com/short-articles/2023-02-13-11ty-conditional-canonical/)
