@julio
Implementing canonical URLs in Django involves creating a consistent representation of URLs for your web pages to avoid duplicate content issues and tell search engines which version of a URL is the preferred one. Here's a step-by-step guide on how to implement canonical URLs in a Django application:
To add a canonical link element in the HTML, update the <head>
section of your templates:
1 2 3 4 |
<head> <!-- Other head elements --> <link rel="canonical" href="{{ request.build_absolute_uri }}"> </head> |
The request.build_absolute_uri
will generate the full URL for the current request, which is useful for generating the canonical URL.
If you need to use the canonical URL in various templates, it might be useful to define a context processor that makes the canonical URL available in all templates. This can be done as follows:
Create a new file, for example, context_processors.py
inside one of your apps or a utils
directory:
1 2 3 |
# myapp/context_processors.py def canonical_url(request): return {'canonical_url': request.build_absolute_uri()} |
Add the newly created context processor to the TEMPLATES
settings:
1 2 3 4 5 6 7 8 9 10 11 12 |
# settings.py TEMPLATES = [ { # Other TEMPLATE settings 'OPTIONS': { 'context_processors': [ # Default context processors 'myapp.context_processors.canonical_url', ], }, }, ] |
Now you can use canonical_url
in any template:
1
|
<link rel="canonical" href="{{ canonical_url }}"> |
If you need different canonical URLs for different views (for example, view with query parameters), you can customize how you build the canonical URL:
In your views, you can pass a custom canonical URL:
1 2 3 4 5 6 |
from django.shortcuts import render def my_view(request): canonical_url = request.build_absolute_uri(request.path) context = {'canonical_url': canonical_url} return render(request, 'my_template.html', context) |
Use request.path
to avoid including query strings, ensuring the canonical URL only points to the main content URL.
Ensure when accessing different pages in your application, the <link rel="canonical">
properly reflects the desired canonical version of the URL. Verify using tools like Google's URL Inspection to ensure it's implemented correctly.
By following these steps, you can ensure that your Django site has a consistent approach to handling canonical URLs, improving SEO and avoiding issues with duplicate content.