How to set canonical urls in Django templates

Usually the same web page can be accessed at least from 4 different url:

What do you mean by:

What you consider a canonical host reference has to be defined somewhere.

(Which combinations of those host references are actually usable is determined outside your Django project. For someone who does “https-only”, the last two are not valid, and for a group using multiple servers and subdomains, the first two could be different sites.)

All four version is valid in my case intentionally. So the same page can be accessed in 4 different ways. the www prefix is handled in DNS, the http/https is handled in nginx.conf by redirect. The only purpose I need canonical url to avoid duplicate content from SEO point of view.

So, my only goal is to put the following code to the head section of the templates:

<link rel="canonical" href="https://example.com/page1" />

I am looking for a way to use some context variables and create this. I do not think so that half hardcoding is “django friendly” and elegant solution like this:

<link rel="canonical" href="https://example.com{% url 'view_name' %}" />

Or maybe a context processor based solution is the best practice, like in this blog post:

def context(request):
    # stuff needed before defining context
    context = {
        'CANONICAL_PATH': request.build_absolute_uri(request.path),
        # any other context variables needed
    }

    return context

I agree - I think either a custom tag or context processor would be your best options here.

Either one would let you use a setting from your settings.py file as the definition, or from some other source.