How to provide Django's canonical URL HttpResponseRedirect?

This question is very similar to the one I just asked href: can I get google search results to use / display the final redirect url? , but now the question is specific to Django.

My site has web page URLs that use the following format:

www.mysite.com/id/pretty_title 

The first page links to these pages, but href actually contains some parameters:

  www.mysite.com/id/?some_ugly_parameters_to_let_me_know_what_search_it_is_from 

Then it redirects to

 www.mysite.com/id/pretty_title 

which shows the page.

My problem is that Google Search results show the link to the page as an ugly URL, rather than a pretty redirected one.

I found out that I need to provide a canonical link. But how can I do this when an ugly url page never exists, at least not in the way I wrote?

What happens on the server side is that presenting the ugly URL does the redirection:

 return HttpResponseRedirect(pretty_url) 
+6
source share
3 answers

You can simply put it as part of the HTML returned from the Django template in the <head> section. Do you have base.html in your Django? You can set {% block %} as a placeholder for the canonical URL, and then set this value on each individual page to {% extends base.html %}

base.html

 <html> <head> <link rel="canonical" href="{% block canonical_url %}{% endblock %}"> </head> ... 
+6
source

I think this is the right template tag you are looking for. {{request.build_absolute_uri}}

+10
source
 <link rel="canonical" href="https://{{ request.get_host }}{% url 'your_url_name' your_url_parametrs %}"> 

In my practice, the most understandable and beautiful option was (similar to Jim Bob's option)

0
source

All Articles